C#停止BackgroundWorker的BackgroundWorker

由网友(愿岁月可回首)分享简介:我有关于BackgroundWorker的问题。I have question about backgroundworker.我在BackgroundWorker的死循环。我怎样才能阻止它?I have endless loop in backgroundworker. How can I stop it?推荐...

我有关于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 有内置的取消支持。要取消后台工作呼叫BackgroundWorker.CancelAsync.你也需要修改职工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)
{
    ...
}

有关取消工作,你还需要将属性设置BackgroundWorker.WorkerSupportsCancellation以。这可以在设计完成。

For cancellation to work you also need to set the property BackgroundWorker.WorkerSupportsCancellation to true. This can be done in the designer.

阅读全文

相关推荐

最新文章