Search code examples
c#backgroundworker

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?


Solution

  • 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);
    }