C#停止BackgroundWorker的 [英] C# Stop BackgroundWorker
问题描述
我有关于BackgroundWorker的问题。
I have question about backgroundworker.
我在BackgroundWorker的死循环。我怎样才能阻止它?
I have endless loop in backgroundworker. How can I stop it?
推荐答案
将其更改为一个非死循环。
Change it to a non-endless loop.
在的BackgroundWorker
有内置的取消支持。要取消后台工作呼叫<一href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx"><$c$c>BackgroundWorker.CancelAsync$c$c>.你也需要修改职工code,以检查取消的文档中提到:
The BackgroundWorker
has built-in support for cancellation. To cancel a background worker call BackgroundWorker.CancelAsync
. Also you need to modify the worker code to check for cancellation as mentioned in the documentation:
CancelAsync提交请求终止挂起的后台操作和设置CancellationPending属性为true。
CancelAsync submits a request to terminate the pending background operation and sets the CancellationPending property to true.
当你调用CancelAsync,您的辅助方法有机会停止执行并退出。工人code应定期检查CancellationPending属性,看它是否已经被设置为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.
因此,举例来说,如果你有这样的死循环在你的工作线程:
So for example if you have this endless loop in your worker thread:
while (true)
{
...
}
,那么你可以将其更改为:
then you could change it to:
while (!backgroundWorker.CancellationPending)
{
...
}
有关取消工作,你还需要将属性设置<一个href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.workersupportscancellation.aspx"><$c$c>BackgroundWorker.WorkerSupportsCancellation$c$c>以真
。这可以在设计完成。
For cancellation to work you also need to set the property BackgroundWorker.WorkerSupportsCancellation
to true
. This can be done in the designer.
这篇关于C#停止BackgroundWorker的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!