如何在c#中创建多个线程

我需要收听机器中的所有串口。 假如我的机器有4个串口,我必须创建4个线程并分别用附加的线程开始监听每个端口。

我用这段代码来获取机器中的端口数量。

private SerialPort comPort = new SerialPort(); public void GetAllPortNamesAvailable() { string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { //How to start a thread here ?? } } public void AssignThreadtoPort() { string msg = comPort.ReadLine(); this.GetMessageRichTextBox("Message : " + msg + "\n"); } 

阅读评论后,我使用此代码,但没有收到消息..问题是什么?

 public void AssignThreadsToPorts() { string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { SerialPort sp = new SerialPort(); sp.PortName = port; sp.Open(); new Thread(() => { if (sp.IsOpen) { string str = sp.ReadLine().ToString(); MessageBox.Show(str); } }).Start(); } } 

你可以使用线程池 :

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

或手动创建和启动线程 :

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