multithreading - How to cancel a backgroundworker with multiple methods in c# optimal? -


i have backgroundworker few different functions , loops. every example found on internet 1 loop respectively 1 function. want know if there exists short solution cancel worker button. know 2 solutions not optimal think.

1: add if/else every function/loop -> long , confusing code

loop {                 if (worker.cancellationpending == true)       {           e.cancel = true;           break;       }       else       {           calculation       } } 

2: kill backgroundworker thread abort here (how “kill” background worker completely?)

i want calculation stops after hitting cancel button no matter loop or function executed @ moment. there better oppotunities mine?

edit: , don't know why how can cancel task without loop should solve problem because have many different loops.

when working background worker, choice have pepper code checks see if operation has been cancelled.

how implement entirely you, i'd want check @ start of every potentially-time-consuming operation, e.g. database query or file system operation, , @ beginning of every loop.

now, you've noticed, gets trickier when have multiple methods involved. in case, storing worker in class-level field appropriate can check cancellation status every method wherever applicable.

one useful approach utilize own custom exception class. wrap code in top-level method within try-catch block, , whenever find out background worker has been cancelled somewhere deeper within call stack, throw instance of exception handled catch block.

here's simple example worked up.

class cancellationexception : exception {     public object state { get; private set; }      public cancellationexception(object state)     {         this.state = state;     } }  private void dosomething() {     if (_worker.cancellationpending)     {         throw new cancellationexception("cancelled blah blah");     } }  private void backgroundworker1_dowork(object sender, doworkeventargs e) {     try     {         dosomething();     }     catch (cancellationexception ce)     {         e.cancel = true;     } } 

note state property in exception used determine in process cancellation hit can clean resources, etc.


Comments