当前位置: 动力学知识库 > 问答 > 编程问答 >

.net - C# Stop BackgroundWorker

问题描述:

I have question about backgroundworker.

I have endless loop in backgroundworker. How can I stop it?

网友答案:

Change it to a non-endless loop.

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 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.

So for example if you have this endless loop in your worker thread:

while (true)
{
    ...
}

then you could change it to:

while (!backgroundWorker.CancellationPending)
{
    ...
}

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: