如何取消带有睡眠的后台工作者?
我无法取消其中包含 Thread.Sleep(100) 的后台工作线程。
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
int count;
try
{
count = int.Parse(textBox3.Text);
for (int i = 0; i < count; i++)
{
backgroundWorker1.ReportProgress((int)(((double)(i + 1) / count) * 1000));
//Computation code
Thread.Sleep(int.Parse(textBox4.Text));
}
}
catch (Exception ex)
{
request.DownloadData(url);
MessageBox.Show(ex.Message);
}
}
private void cancel_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
progressBar1.Value = 0;
}
如果我删除 Thread.Sleep(100) ,那么取消会起作用,但否则它会继续进行(进度条不会停止)。
编辑:添加了其余代码
I'm having trouble canceling a background worker that has a Thread.Sleep(100)
in it.
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
int count;
try
{
count = int.Parse(textBox3.Text);
for (int i = 0; i < count; i++)
{
backgroundWorker1.ReportProgress((int)(((double)(i + 1) / count) * 1000));
//Computation code
Thread.Sleep(int.Parse(textBox4.Text));
}
}
catch (Exception ex)
{
request.DownloadData(url);
MessageBox.Show(ex.Message);
}
}
private void cancel_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
progressBar1.Value = 0;
}
If I remove the Thread.Sleep(100)
then the cancel works but otherwise it just keeps going (the progress bar doesn't stop).
EDIT: Added the rest of the code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您调用 CancelAsync 时,它只是将名为
CancellationPending
的属性设置为 true。现在,您的后台工作人员可以而且应该定期检查此标志是否为真,以优雅地完成其操作。因此,您需要将后台任务分成几部分,您可以在其中检查取消情况。When you call CancelAsync it just sets a property called
CancellationPending
to true. Now your backgroundworker can, and should, periodically check if this flag is true, to gracefully finish its operation. So you need to split your background task into pieces where you can check for cancelation.当您想要取消后台线程时,请使用 Thread.Interrupt 从 WaitSleepJoin 状态退出。
http://msdn.microsoft.com/en-us /library/system.threading.thread.interrupt.aspx
Use Thread.Interrupt to exit from WaitSleepJoin state when you want to cancel the background thread.
http://msdn.microsoft.com/en-us/library/system.threading.thread.interrupt.aspx