santBart
santBart

Reputation: 2496

BackgroundWorker support cancelation

I use BackgroundWorker but have problem with reporting cancellation:

BackgroundWorker worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
    expensiveMethod();
}

DoWork should periodically check if cancellation request is pending. How to do this, if I cant modify expensiveMethod?

Upvotes: 3

Views: 3011

Answers (3)

Fernando
Fernando

Reputation: 4028

Use a Task. Tasks uses threads from the ThreadPool (such as BackgroundWorker), but they support cancellation (via CancellationToken), without the need of exceptions.

Upvotes: 0

Frank Bollack
Frank Bollack

Reputation: 25206

If you cannot modify your expensiveMethod() then there is no direct way to process cancellation.

If expensiveMethod() is working on some big chunk of data, maybe you can split that data and process smaller (not so lengthy) chunks in a loop and after each iteration check for the cancel flag. Something like this:

//...
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
   do
   {
       provideNextChunk();
       expensiveMethod();
   }
   while (hasMoreData && !args.Cancel);
}

Upvotes: 2

Aoi Karasu
Aoi Karasu

Reputation: 3825

BackgroundWorker is designed to work with threads that actually CAN respond to cancellation requests. If your expensiveMethod() cannot do it, I advise you to use System.Threading.Thread instead. Run it as background thread, and use Thread.Abort() to cancel it.

Upvotes: 1

Related Questions