Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackgroundWorker.CancelAsync() causes "BackgroundWorker does not support cancellation." error

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?

like image 417
Louis Waweru Avatar asked May 01 '12 04:05

Louis Waweru


People also ask

How do I stop DoWork BackgroundWorker?

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.

What is use of BackgroundWorker in C#?

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.

What is BackgroundWorker in Winforms?

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.


1 Answers

You'll need to set the BackgroundWorker.WorkerSupportsCancellation Property to true.

like image 130
Jay Riggs Avatar answered Sep 28 '22 14:09

Jay Riggs