質問

I'm writing a windows service that responds to IMAP push notifications. When a notification is received I queue a user work item using ThreadPool. (The method it invokes puts some things in a database and etc).

At some point I want to stop my service which will stop the ThreadPool from queuing additional threads and wait until there are no open threads that are doing work.

//Pseudo code
public void StopService()
{
    while (true)
    {
        if (ThreadPool.ActiveThreads == 0)
        {
            //disconnect imap
            //stop service
        }
    }
}

Even better would be a way to tell the ThreadPool that I want to be notified that it has no active threads so that I don't have to poll it in a while loop.

This question uses a thread safe counter which is one way to figure out if the ThreadPool has any open threads, but surely there must be a flag or some method/property off the ThreadPool class to determine this?

役に立ちましたか?

解決

I would suggest you hook up all your individual work items to a ManualResetEvent then queue up all your work items in the ThreadPool and then call WaitHandle.WaitAll(myResetEvents); to wait until all of your work items are complete, then close your service down, etc.

Program Flow

  1. Start Service
  2. Start Listening
  3. Queue Work Items
  4. Stop Listening for new items
  5. Wait for all items to finish -WaitHandle.WaitAll(allMyQueuedWorkitems)
  6. Stop Service
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top