c# - Quitting BackgroundWorker using flag -


imagine have such code:

 private bool flag = false;  public someclass()  {      public void setup()     {         worker = new backgroundworker();         worker.dowork += worker_dowork;          if(!worker.isbusy)             worker.runworkerasync();     }      void worker_dowork(object sender, doworkeventargs e)     {         if(flag == true)           return;         //whatever want background thread do...         someclass.somestaticmethodwhichhasloopinside();     } } 

when user clicks exit button in application can set flag=true inside - right way stop thread started backgroundworker? want when application wants quit - stop thread. or automatically killed?

no. don't that. not work expected. flag field isn't declared volatile; possible true value of field isn't flushed memory yet. other thread still see flag false because caches own copy of value , backgroundworker may never end.

instead, call backgroundworker.cancelasync , check backgroundworker.cancellationpending boolean inside dowork event handler.

private void onexit(..) {     worker.cancelasync(); } 

so dowork method become

void worker_dowork(object sender, doworkeventargs e) {     while(!worker.cancellationpending)     {         //whatever want background thread do...     } } 

if don't have loop, need check cancellationpending property time time.

void worker_dowork(object sender, doworkeventargs e) {     if(worker.cancellationpending)         return;     //do something..     if(worker.cancellationpending)         return;     //do other thing..     if(worker.cancellationpending)         return;     //do else.. } 

i want when application wants quit - stop thread. or automatically killed?

it killed automatically clr since thread background thread. but, don't rely on fact because don't know thread executing @ time clr kills thread. example, might have been writing file in case you'd left corrupted file.

consequences can worse, recommended stop threads gracefully.

question asked in comments: how can cancel when loop in other method?

it seems you're using .net4.5. can take advantage of cancellationtokensource , cancellationtoken. may consider using tpl , async-await features make life lot easier.

private cancellationtokensource tokensource = new cancellationtokensource();  private void onexit(..) {     tokensource.cancel(); }  void worker_dowork(object sender, doworkeventargs e) {     //whatever want background thread do...     someclass.somestaticmethodwhichhasloopinside(tokensource.token); }  class someclass {     public static void somestaticmethodwhichhasloopinside(cancellationtoken token)     {         while (!token.iscancellationrequested)         {             //do         }     } } 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -