Workaround for the WaitHandle.WaitAll 64 handle limit?

前端 未结 9 1923
孤独总比滥情好
孤独总比滥情好 2020-11-28 04:19

My application spawns loads of different small worker threads via ThreadPool.QueueUserWorkItem which I keep track of via multiple ManualResetEvent

9条回答
  •  清歌不尽
    2020-11-28 05:00

    Adding to dtb's answer you can wrap this into a nice simple class.

    public class Countdown : IDisposable
    {
        private readonly ManualResetEvent done;
        private readonly int total;
        private long current;
    
        public Countdown(int total)
        {
            this.total = total;
            current = total;
            done = new ManualResetEvent(false);
        }
    
        public void Signal()
        {
            if (Interlocked.Decrement(ref current) == 0)
            {
                done.Set();
            }
        }
    
        public void Wait()
        {
            done.WaitOne();
        }
    
        public void Dispose()
        {
            ((IDisposable)done).Dispose();
        }
    }
    

提交回复
热议问题