C# Stop BackgroundWorker

前端 未结 1 807
猫巷女王i
猫巷女王i 2021-01-22 01:21

I have question about backgroundworker.

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

相关标签:
1条回答
  • 2021-01-22 01:44

    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.

    0 讨论(0)
提交回复
热议问题