How can I accomplish ThreadPool.Join?

浪子不回头ぞ 提交于 2019-11-30 15:54:40

问题


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?


回答1:


You could create an event (e.g. ManualResetEvent) in each thread, and keep it in a synchronised list (using the lock construct). 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.




回答2:


The standard pattern for doing this is to use a counter which holds the number of pending work items and one ManualResetEvent that is signalled when the counter reaches zero. This is generally better than using a WaitHandle for each work item as that does not scale very well when there are a lot of simultaneous work items. Plus, some of the static WaitHandle method only accept a maximum of 64 instances anyway.

// Initialize to 1 because we are going to treat the current thread as
// a work item as well. This is to avoid a race that could occur when
// one work item gets queued and completed before the next work item
// is queued.
int count = 1;
var finished = new ManualResetEvent(false); 
try 
{ 
  while (...)
  {  
    Interlocked.Increment(ref counter);
    ThreadPool.QueueUserWorkItem( 
      delegate(object state) 
      { 
        try 
        { 
          // Your task goes here. 
        } 
        finally 
        { 
          // Decrement the counter to indicate the work item is done.
          if (Interlocked.Decrement(ref count) == 0) 
          { 
            finished.Set(); 
          } 
        } 
      }); 
  } 
}
finally
{
  // Decrement the counter to indicate the queueing thread is done.
  if (Interlocked.Decrement(ref count) == 0) 
  { 
    finished.Set(); 
  } 
}
finished.WaitOne(); 


来源:https://stackoverflow.com/questions/3426718/how-can-i-accomplish-threadpool-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!