use*_*064 2 .net c# backgroundworker
我的应用程序使用后台工作程序在循环内做一些工作.我有它,所以在每次循环迭代时,它检查取消挂起是否为真,如果是,则打破循环.好的,我的应用程序一旦完成循环的当前迭代就会停止处理.问题是我认为后台工作程序仍然在运行 - 如果我单击按钮再次开始处理,我会收到一个错误,说后台工作人员正忙.
我打算处理这个工作人员,但是当表单运行时就会创建它,所以如果我处理它,那就不能再开始工作了.我真正想做的是告诉后台工作人员它是完整的,如果我点击"停止处理"按钮,那么当我点击开始按钮时它就可以再次开始处理了!
我打算尝试这个:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (!backgroundWorker1.CancellationPending)
{
// Start processing in a background thread so the GUI remains responsive,
// pass in the name of the text file produced by
// PFDR FilenameLogic(txtLetterType.Text);
}
}
Run Code Online (Sandbox Code Playgroud)
创建工作线程时,设置worker.WorkerSupportsCancellation为true.现在里面的DoWork处理程序,您必须定期(最常见的是,在一些循环的开始,等)检查worker.CancellationPending-如果这是真的,设置e.Cancel = true;(这样就可以区分删除完成),清理和退出(return;).现在您的取消按钮可以调用worker.CancelAsync();,它将采取适当的行动.
与Marc Gravell相同的答案,但你似乎没有遵循.
你在设置e.cancel = true吗?
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i * 10);
}
}
}
Run Code Online (Sandbox Code Playgroud)