c# - 使用 backgroundworker 进行时间控制

标签 c# .net winforms multithreading backgroundworker

我有一个将数据抓取到 csv 文件的应用程序,程序每 5 秒抓取一次数据。问题是在后台发生这种情况时我无法执行任何其他操作。我正在使用计时器来完成工作。

我发现了 backgroundworker 控件,我尝试使用它,我在表单减速方法中设置了 RunWorkerAsync(在 initializeComponent 之后) 但它并没有开始。我在下面给出了 backgroundworker 的编码。

这里有什么需要更正的吗?如果这不是正确的方法,那么在我能够继续进行其他形式事件的同时让后台进程发生的最佳方法是什么。谢谢

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    //int a = (int)(e.Argument);
    if (backgroundWorker1.CancellationPending)
    {
        e.Cancel = true;
    }
    else 
    {
        timerQuote.Enabled = true;
        timerQuote.Start();
    }
}


private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled) 
    {
        MessageBox.Show("grabbing is terminated");
    }
}

//Form decleration
public Form1()
{
    InitializeComponent();
    backgroundWorker1.RunWorkerAsync();
    ...
}

最佳答案

Timer 必须在 UI 线程上启动,否则它将静默失败。此外,您无需自己设置 enabled 属性 - 当您调用 Start 方法时,它会变为 true。

另一种可能是:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        var t = new Timer();
        t.Tick += new EventHandler(GrabData);
        t.Interval = 5000;
        t.Start();
    }

    void GrabData(object sender, EventArgs e)
    {
        var data = Task.Factory.StartNew(() =>
        {
            // get and return data
        });

        // do something with the data.Result
    }
}

关于c# - 使用 backgroundworker 进行时间控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8251787/

相关文章:

c# - 检查属性是否具有指定的属性,然后打印它的值

.net - 新遗迹在运行时更改应用程序名称.NET

c# - 如何在 C# 中显示对象的数据?

c# - 如何防止事件导致其自身的事件在 C# 中触发?

c# - 在 Visual Studio 中删除未使用的 C# 代码

c# - web.config 中的 optimizeCompilations 有什么作用?

c# - 停止自动隐藏托盘通知图标

.net - System.Drawing.Font - 更改字母间距?

c# - 泛型类型的术语

c# - 有没有一种方法可以将 DataRow 映射到类的对象