C# Waiting for multiple threads to finish

后端 未结 5 1686
滥情空心
滥情空心 2020-11-28 12:30

I have a windows forms app that I am checking all the serial ports to see if a particular device is connected.

This is how I spin off each thread. The below code is

5条回答
  •  温柔的废话
    2020-11-28 12:53

    You can use a CountDownLatch:

    public class CountDownLatch
    {
        private int m_remain;
        private EventWaitHandle m_event;
    
        public CountDownLatch(int count)
        {
            Reset(count);
        }
    
        public void Reset(int count)
        {
            if (count < 0)
                throw new ArgumentOutOfRangeException();
            m_remain = count;
            m_event = new ManualResetEvent(false);
            if (m_remain == 0)
            {
                m_event.Set();
            }
        }
    
        public void Signal()
        {
            // The last thread to signal also sets the event.
            if (Interlocked.Decrement(ref m_remain) == 0)
                m_event.Set();
        }
    
        public void Wait()
        {
            m_event.WaitOne();
        }
    }
    

    Example how to use it:

    void StartThreads
    {
        CountDownLatch latch = new CountDownLatch(availPorts.Count);
    
        foreach (cpsComms.cpsSerial ser in availPorts)
        {
            Thread t = new Thread(new ParameterizedThreadStart(lookForValidDev));
    
            //start thread and pass it the port and the latch
            t.Start((object)new Pair(ser, latch));
    
        }
    
        DoSomeWork();
    
        // wait for all the threads to signal
        latch.Wait();
    
        DoSomeMoreWork();
    }
    
    // In each thread
    void NameOfRunMethod
    {
        while(running)
        {
            // do work
        }
    
        // Signal that the thread is done running
        latch.Signal();
    }
    

提交回复
热议问题