I am writing a windows service that uses ThreadPool.QueueUserWorkItem(). Each thread is a short-lived task.
When the service is stopped, I need to make sure that all the threads that are currently executing complete. Is there some way of waiting until the queue clears itself?
You could create an event (e.g.
ManualResetEvent) in each thread, and keep it in a synchronised list (using thelockconstruct). Set the event or remove it from the list when the task is finished.When you want to join, you can use
WaitHandle.WaitAll(MSDN documentation) to wait for all the events to be signalled.It’s a hack, but I can’t see how to reduce it to anything simpler!
Edit: additionally, you could ensure that no new events get posted, then wait a couple of seconds. If they are indeed short-lived, you’ll have no problem. Even simpler, but more hacky.
Finally, if it’s just a short amount of time, the service won’t exit until all threads have died (unless they are background threads); so if it’s a short amount of time, the service control manager won’t mind a second or so – you can just leave them to expire – in my experience.