我对 backgroundworker 有疑问。
我在 backgroundworker 中有无限循环。我该如何阻止它?
最佳答案
改成非无限循环
BackgroundWorker
内置了对取消的支持。取消后台 worker 调用 BackgroundWorker.CancelAsync
.您还需要修改工作人员代码以检查文档中提到的取消:
CancelAsync submits a request to terminate the pending background operation and sets the CancellationPending property to true.
When you call CancelAsync, your worker method has an opportunity to stop its execution and exit. The worker code should periodically check the CancellationPending property to see if it has been set to true.
例如,如果您的工作线程中有这个无限循环:
while (true)
{
...
}
那么你可以把它改成:
while (!backgroundWorker.CancellationPending)
{
...
}
要使取消生效,您还需要设置属性 BackgroundWorker.WorkerSupportsCancellation
为 true
。这可以在设计器中完成。
关于C# 停止 BackgroundWorker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4618415/