c# - Waiting the main thread to stop until a task is processed by an async thread -


lets have following program in start method, delegates long running task thread. when stop method called, need make sure worker thread completes executing current task , not leave in middle of it. if has completed task , in sleep state, can stop immidiately.

please guide me on how should it.

    static int itemsprocessed = 0;     static thread worker;     static void start()     {         var ts = new threadstart(run);         worker = new thread(ts);         worker.start();     }      static void stop()     {         //wait until 'worker' completes processing current item.         console.writeline("{0} items processed", itemsprocessed);     }      static void run(object state)     {         while (true)         {             alongrunningtask();             itemsprocessed++;             thread.sleep(1000);         }     } 

one way use volatile variable communicate betweej 2 threads. this, create "volatile bool isrunning;". in start set value true, in run chage while loop "while (isrunning)". in stop, set isrunning equal false , call worker.join(). cause run method exit when finishes processing current item, , join wait until thread exits.

the last thing need access itemsprocessed in thread-safe way. in current code there no way know if stop sees date value of itemsprocessed since changed thread. 1 option create lock itemsprocessed , hold lock inside of run, , acquire lock before writeline statement in stop.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -