How to create multiple threads in c#

前端 未结 1 1690
臣服心动
臣服心动 2021-01-16 09:25

I am need to listen to all the serial ports in my machine. Say if my machine has 4 serial ports, i have to create 4 threads and start listening to each port with the attache

相关标签:
1条回答
  • 2021-01-16 10:13

    You could use the thread pool:

    string[] ports = SerialPort.GetPortNames();
    foreach (string port in ports)
    {
        ThreadPool.QueueUserWorkItem(state =>
        {
            // This will execute in a new thread
        });
    }
    

    or create and start the threads manually:

    string[] ports = SerialPort.GetPortNames();
    foreach (string port in ports)
    {
        new Thread(() => 
        {
            // This will execute in a new thread
        }).Start();
    }
    
    0 讨论(0)
提交回复
热议问题