Вопрос

I have multiple serial devices connected to my PC and I am working on a program that allows users select as many as ports they want and then the program will dynamically creates TabPage and adds them to TabControl.

Each tab page will also have a multiline TextBox that will show the incoming data from the assigned serialport to it.

Here is my code that tries to create these controls dynamically:

private void AddSerialPort(string portName)
{
    var page = new TabPage(portName);

    page.Text = portName;

    var tb = new TextBox();
    tb.Name = portName;
    tb.Dock = DockStyle.Fill;
    tb.BackColor = Color.Black;
    tb.ForeColor = Color.White;
    tb.Multiline = true;
    page.Controls.Add(tb);
    tabControlActiveSerialPorts.TabPages.Add(page);    

    //Define serial port
    var sp = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One);                

    sp.DataReceived += delegate
    {
        if (tb.InvokeRequired)
        {
            tb.Invoke(new Action(() =>
            {
                var incoming = sp.ReadExisting();
                tb.Text += incoming;                
            }));
        }
        else
        {
            var incoming = sp.ReadExisting();
            tb.Text += incoming;
        }
    };

    sp.Open();
}

The problem is, If I only add a single SerialPort, it works fine and textbox gets filled. But as soon as I add another SerialPort, After few seconds, either the first or the second added SerialPort will stop working, while the other one still works (this is completly random either first or second stops filling data in textbox, and NO its not my hardware!) I mean the textbox that what designated for it will not get filled anymore.

I don't receive any error from debugger...this just does not work! Any idea what can be the problem?

I have to mention if I only add 1 serial port, it works OK!

I have tried BeginInvoke instead of Invoke but it didnt change anything.

Это было полезно?

Решение

It might be that the SerialPort objects get disposed. Try to add every new object to the list:

class Class
{
    List<SerialPort> ports = new List<SerialPort>();

    private void AddSerialPort(string portName)
    {
       ...
       var sp = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One);
       ports.Add(sp);
       ...
    }       
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top