be notified when all background threadpool threads are finished

后端 未结 7 1906
星月不相逢
星月不相逢 2020-12-16 01:37

I have a scenario when I start 3..10 threads with ThreadPool. Each thread does its job and returns to the ThreadPool. What are possible options to be notified in main thread

7条回答
  •  抹茶落季
    2020-12-16 02:13

    Try this: https://bitbucket.org/nevdelap/poolguard

    using (var poolGuard = new PoolGuard())
    {
        for (int i = 0; i < ...
        {
            ThreadPool.QueueUserWorkItem(ChildThread, poolGuard);
        }
        // Do stuff.
        poolGuard.WaitOne();
        // Do stuff that required the child threads to have ended.
    
    void ChildThread(object state)
    {
        var poolGuard = state as PoolGuard;
        if (poolGuard.TryEnter())
        {
            try
            {
                // Do stuff.
            }
            finally
            {
                poolGuard.Exit();
            }
        }
    }
    

    Multiple PoolGuards can be used in different ways to track when threads have ended, and handles threads that haven't started when the pool is already closed.

提交回复
热议问题