日期:2014-05-19  浏览次数:20890 次

请问BackgroundWorker线程能随时中止么?
比如
                void   workerThread_DoWork(object   sender,   DoWorkEventArgs   e)
                {
                        Thread.Sleep(1000000);
                }
能随时直接中止掉么?还是一定要Sleep完才能操作?

------解决方案--------------------
参见MSDN:

BackgroundWorker.CancelAsync 方法
请求取消挂起的后台操作。
CancelAsync 提交终止挂起的后台操作的请求,并将 CancellationPending 属性设置为 true。

调用 CancelAsync 时,辅助方法可以停止其执行并退出。辅助代码应定期检查 CancellationPending 属性,查看是否已将该属性设置为 true。

请注意,DoWork 事件处理程序中的代码有可能在发出取消请求时完成其工作,轮询循环可能会错过设置为 true 的 CancellationPending。在这种情况下,即使发出了取消请求,RunWorkerCompleted 事件处理程序中 System.ComponentModel.RunWorkerCompletedEventArgs 的 Cancelled 标志也不会设置为 true。这种情况被称作争用状态,它是多线程编程中的常见问题。有关多线程设计问题的更多信息,请参见托管线程处理的最佳做法。

下面的代码示例演示如何使用 CancelAsync 方法取消异步(“后台”)操作。

private void cancelAsyncButton_Click(System.Object sender,
System.EventArgs e)
{
// Cancel the asynchronous operation.
this.backgroundWorker1.CancelAsync();

// Disable the Cancel button.
cancelAsyncButton.Enabled = false;
}


------解决方案--------------------
BackgroundWordker 是等代码执行完了再重新计时.
Timer 是不管代码执行情况,到时间都会触发.