I need to make sure a BackgroundWoker isn't busy before being called, so I check IsBusy
and call CancelAsync if it is:
if (bgWorker.IsBusy)
bgWorker.CancelAsync();
But if IsBusy
is true, an InvalidOperationException exception occurs in CancelAsync()
saying "BackgroundWorker does not support cancellation."
The documentation makes usage seem pretty straightforward, so what am I doing wrong? How can I cancel the job?
CancelAsync doesn't actually abort your thread or anything like that. It sends a message to the worker thread that work should be cancelled via BackgroundWorker. CancellationPending . Your DoWork delegate that is being run in the background must periodically check this property and handle the cancellation itself.
BackgroundWorker makes the implementation of threads in Windows Forms. Intensive tasks need to be done on another thread so the UI does not freeze. It is necessary to post messages and update the user interface when the task is done.
A BackgroundWorker component executes code in a separate dedicated secondary thread. In this article, I will demonstrate how to use the BackgroundWorker component to execute a time-consuming process while the main thread is still available to the user interface.
You'll need to set the BackgroundWorker.WorkerSupportsCancellation Property to true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With