c# - Exiting a thread that does not have a loop -


i need way stop worker thread not contain loop. application starts thread, thread creates filesystemwatcher object , timer object. each of these has callback functions. have done far add volatile bool member thread class, , use timer check value. i'm hung on how exit thread once value set.

    protected override void onstart(string[] args)     {       try       {         watcher newwatcher = new watcher(...);         thread watcherthread = new thread(newwatcher.watcher.start);         watcherthread.start();       }       catch (exception ex)       {           ...       }     }  public class watcher {     private volatile bool _stopthread;      public watcher(string filepath)     {         this._filepath = filepath;         this._lastexception = null;          _stopthread = false;         timercallback timerfunc = new timercallback(onthreadtimer);         _threadtimer = new timer(timerfunc, null, 5000, 1000);     }         public void start()     {         this.createfilewatch();                 }      public void stop()     {         _stopthread = true;     }      private void createfilewatch()     {         try         {             this._filewatcher = new filesystemwatcher();             this._filewatcher.path = path.getdirectoryname(filepath);             this._filewatcher.filter = path.getfilename(filepath);             this._filewatcher.includesubdirectories = false;             this._filewatcher.notifyfilter = notifyfilters.lastwrite;             this._filewatcher.changed += new filesystemeventhandler(onfilechanged);              ...              this._filewatcher.enableraisingevents = true;         }         catch (exception ex)         {             ...         }     }      private void onthreadtimer(object source)     {         if (_stopthread)         {             _threadtimer.dispose();             _filewatcher.dispose();             // exit thread here (?)         }     }      ... } 

so can dispose the timer / filewatcher when thread told stop - how actual exit/stop thread?

rather boolean flag, suggest using manualresetevent. thread starts filesystemwatcher, waits on event. when stop called, sets event:

private manualresetevent threadexitevent = new manualresetevent(false);  public void start() {     // set watcher     this.createfilewatch();      // wait exit event ...     threadexitevent.waitone();      // tear down watcher , exit.     // ... }  public void stop() {     threadexitevent.set(); } 

this prevents having use timer, , you'll still notifications.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -