Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to immediately cancel a working BackgroundWorker?

I have a time taking process in DoWork of my BackgroundWorker.

Whenever I try to Cancel the job by backgroundWorker1.CancelAsync(), the backgroundWorker1.CancellationPending becomes Pending and I should wait for the next iteration in my DoWork to Cancel the job and stepping out of it myself.

Is there any way to Cancel the job immediately after calling it?

like image 374
mammadalius Avatar asked Feb 09 '12 18:02

mammadalius


1 Answers

No. In general you can't safely terminate a thread "immediately", because it may be holding resources that would leak, and more importantly it may be holding locks. You need to structure your worker to respect the cancellation flag and and safely exit as soon as possible.

like image 192
Derek Park Avatar answered Nov 04 '22 12:11

Derek Park