开发者

How to create multiple threads in c#

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 attached thread respectively.

I used this code to get the number of ports in my machine..

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.GetMessageRichTe开发者_JAVA技巧xtBox("Message : " + msg + "\n");
    }

After reading the comments i am using this code but not getting messages.. what is the problem ?

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();
        } 
    } 


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜