C# Waiting for multiple threads to finish

后端 未结 5 1685
滥情空心
滥情空心 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:06

    List threads = new List();
    foreach (cpsComms.cpsSerial ser in availPorts)
    {
        Thread t = new Thread(new ParameterizedThreadStart(lookForValidDev));
        t.Start((object)ser);//start thread and pass it the port
        threads.Add(t);
    }
    foreach(var thread in threads)
    {
        thread.Join();
    }
    

    Edit

    I was looking back at this, and I like the following better

    availPorts.Select(ser =>
          {
              Thread thread = new Thread(lookForValidDev);
              thread.Start(ser);
              return thread;
          }).ToList().ForEach(t => t.Join());
    

提交回复
热议问题