C# Waiting for multiple threads to finish

后端 未结 5 1687
滥情空心
滥情空心 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 13:14

    Use the AutoResetEvent and ManualResetEvent Classes:

    private ManualResetEvent manual = new ManualResetEvent(false);
    void Main(string[] args)
    {
        AutoResetEvent[] autos = new AutoResetEvent[availPorts.Count];
    
        manual.Set();
    
        for (int i = 0; i < availPorts.Count - 1; i++)
            {
    
            AutoResetEvent Auto = new AutoResetEvent(false);
            autos[i] = Auto;
    
            Thread t = new Thread(() => lookForValidDev(Auto, (object)availPorts[i]));
            t.Start();//start thread and pass it the port  
    
        }
        WaitHandle.WaitAll(autos);
        manual.Reset();
    
    }
    
    
    void lookForValidDev(AutoResetEvent auto, object obj)
    {
        try
        {
             manual.WaitOne();
             // do something with obj 
        }
        catch (Exception)
        {
    
        }
        finally
        {
            auto.Set();
        }
    
    
    } 
    

提交回复
热议问题