我有一个将数据抓取到 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/