.net - What's the best way to determine that threads have stopped? -


i have windows service has number of threads need stopped before service stops. i'm using model stopping threads , signalling have been stopped:

threadpool.queueuserworkitem(new waitcallback(delegate {     thread1running = true;      try     {         while (running)         {             autoreset1.waitone(timespan.fromseconds(30.0));              if (running)             {                 // stuff             }         }     }         {         thread1running = false;     } })); 

when comes time shut service stop, set running false , call set() on autoresets out there. instantly signals threads stop sleeping or stop once they've finished processing they're working on. works well. but, part i'm nervous about, verifying has stopped. i'm doing now:

int32 tries = 0; while (tries < 5 && (thread1running || thread2running || thread3running)) {     tries++;      thread.sleep(timespan.fromseconds(5.0)); } 

the main reason don't it's time based, , if 1 of threads in middle of lengthy operation (which quite likely), shut down may not finish in 25 seconds (and it's important of these threads shut down time onstop, code gets run, finishes). can't remove tries because if 1 of threads hangs (they don't, never know), i'm stuck , service never stop.

is there better way verification threads have stopped, preferably 1 isn't time based? or doomed having sort of timeout might need longer (10 tries 30 second sleep, maybe)?

i believe general method doing join on threads. specifics of call depend on threading library you're using, in general join method block until thread has exited (and should return if thread dead). join on threads in sequence, exit. if joins have returned threads have exited.

many threading libraries allow add timeout join, want do. way if 1 of threads hangs exit code doesn't block.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -