C# Stop BackgroundWorker

风格不统一 提交于 2019-12-02 01:59:05

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!