tags:

views:

160

answers:

1

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.GetMessageRichTextBox("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();
        } 
    } 
+4  A: 

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();
}
Darin Dimitrov
@Darin Dimitrov, will the above code create the threads equivalent to number of ports ? And will all the created threads run simultaneously ?? Thanks..
Anuya
If you use the thread pool every time a loop iteration is executed (and you will have the same number of iterations as the number of ports) a thread will be drawn from the pool if available and executed immediately. Once it finishes executing the thread will be returned to the pool. As the thread is executed immediately all the threads will run simultaneously as long as there are threads in the pool. If though your operation is long running it would be preferable to create the threads manually as the overhead of creating threads manually will be overweighted by the lengthy operation.
Darin Dimitrov
i am trying to start the thread manually but not getting the messages...please refer to the code i pasted in the questions part.
Anuya
Try creating and starting the serial port inside the thread.
Darin Dimitrov
@Darin Dimitrov, yeah i did. I have pasted the code above. There was no errors, but it is not receiving the messages.
Anuya