C#BackgroundWorker等待结束
本文关键字:结束 等待 C#BackgroundWorker | 更新日期: 2023-09-27 18:19:29
我正在处理一个需要用线程完成的项目。
我有一个背景工作者来做这项工作。我想要实现的是,当我点击Button3
时,我的后台工作程序将重新启动。我已经试着等待后台工作人员在一段时间内完成Backgroundworker1.IsBusy
,但这永远不会结束。当我点击Button3
时,我得到错误
此BackgroundWorker当前正忙,无法同时运行多个任务
这是我的代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
private void button3_Click_1(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
int x = 0, y = 0, result;
while (true)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
break;
}
else
{
x++;
y++;
result = x + y;
this.label1.Invoke(new MethodInvoker(() => this.label1.Text = result.ToString()));
}
}
}
}//public partial class Form1 : Form
监听完成的事件,然后在那里重新启动工作程序-
private bool restartOnCancel = false;
private void button3_Click_1(object sender, EventArgs e)
{
restartOnCancel = true;
backgroundWorker1.CancelAsync();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true) && restartOnCancel)
{
restartOnCancel = false;
backgroundWorker1.RunWorkerAsync();
}
}
后台工作程序在RunWorkerSync调用之前尚未完成。如果按下按钮3,您可以将一个方法连接到RunWorkerCompleted事件,并在其中调用RunWorkerSync。