[英]How to cancel a background worker with sleep?
我無法取消其中具有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)
則取消有效,但否則它將繼續進行(進度條不會停止)。
編輯:添加了其余的代碼
當您調用CancelAsync時,它只是將名為CancellationPending
的屬性設置為true。 現在,您的后台工作人員可以並且應該定期檢查此標志是否為true,以正常完成其操作。 因此,您需要將后台任務拆分為多個部分,以便檢查取消情況。
private void DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
while(true)
{
if(worker.CancellationPending)
{
e.Cancel = true;
return;
}
Thread.Sleep(100);
}
}
當您想取消后台線程時,請使用Thread.Interrupt退出WaitSleepJoin狀態。
http://msdn.microsoft.com/zh-CN/library/system.threading.thread.interrupt.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.