我正在从事一个需要用线程完成的项目。
我有一个做这项工作的后台工作人员。我想要完成的是当我点击时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