c# - Cancelling background worker tasks -


this question has answer here:

i have background worker performs time consuming task, i'm having trouble cancelling issue because can manage flag cancellation , not terminate process. in order solve it, tried put check points in heavy function want exit , seems not quite efficient. code looks :

in points in heavy function put 2 lines :

if (general.backgroundworker1.cancellationpending) {     return; }  private void button4_click(object sender, eventargs e) //button invokes heavy function {     if (!backgroundworker1.isbusy)         backgroundworker1.runworkerasync(); }  private void backgroundworker1_dowork(object sender, doworkeventargs e) {     heavyfunction(this);     if (backgroundworker1.cancellationpending)     {         e.cancel = true;         return;     } }  private void backgroundworker1_runworkercompleted_1(object sender, runworkercompletedeventargs e) {     if (e.cancelled)     {         statuslabel.text = "status: cancelled";     }     else if (e.error != null)     {         statuslabel.text = "error!";     }     else     {         code;     } }  private void cancelsdoutloop_click(object sender, eventargs e) {     if (backgroundworker1.isbusy)     {         backgroundworker1.cancelasync();     } } 

cancel can complicate function implement , left afterthought.

if want cancel heavyfunction (which should longrunningfunction ;) have become cancel aware. said put check points, makes sense.

you can try use more of cancellable method calls accept cancellation token. example task.delay has 2 overloads:

delay(timespan) 

and

delay(timespan, cancellationtoken) 

another strategy split method smaller, shorter tasks.

finally, cancel operation doesn't have instantaneous. may end "cancelling..." status waits moment stop job.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -