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

时间:2010-04-09 08:28:15

标签: c# serial-port

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

1 个答案:

答案 0 :(得分:4)

您可以使用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();
}