Skip to main content
 首页 » 编程设计

c#之C#创建多线程的方法

2024年02月24日28fff_TT

我需要监听我机器上的所有串口。假设我的机器有 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(); 
        }  
    }  

请您参考如下方法:

您可以使用 thread pool :

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

或创建并启动 threads手动:

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