How to block until a thread is returned to the pool?

As part of a windows service, I accept an incoming socket connection using myListener.BeginAcceptSocket(acceptAsync, null)

The function acceptAsyncis executed in a separate thread (as expected).

When a service requests shutdown, I "signal" the streams that have been received and are currently working on sockets to complete.

After each thread ends, I need to block until they are executed. I have a list of topics that I thought I could scroll through and Joineach thread until they were executed.

Howerver seems that these threads do not end, but return to the pool, so Join will always wait.

How to block until a thread is returned to the pool?

+3
source share
3 answers

The canonical template for this is to use a CountdownEvent . The main thread will increase the event to indicate that it is participating, and the worker threads will do the same as soon as they begin. After workflows end, they will reduce the event. When the main thread is ready to wait for completion, it should reduce the event, and then wait for it. If you are not using .NET 4.0, you can get the implementation of the countdown event from part 4 of Joe Albahari for streaming advertising .

public class Example
{
  private CountdownEvent m_Finisher = new CountdownEvent(0);

  public void MainThread()
  {
    m_Finisher.AddCount();

    // Your stuff goes here.
    // myListener.BeginAcceptSocket(OnAcceptSocket, null);

    m_Finisher.Signal();
    m_Finisher.Wait();
  }

  private void OnAcceptSocket(object state)
  {
    m_Finisher.AddCount()
    try
    {
      // Your stuff goes here.
    }
    finally
    {
      m_Finisher.Signal();
    }
  }
}
+3
source

Join . , WaitHandles ( , AutoResetEvent ManualResetEvent), , .

static WaitAll WaitHandle, .

+4

The best way would be to change acceptAsyncit to signal a semaphore, and your main thread can wait for this semaphore.

You do not have much access or control over Threapool threads.

+1
source

Source: https://habr.com/ru/post/1761177/


All Articles