Tey
Tey

Reputation: 1

C# SerialPort DataReceived fails to Trigger after random time

I'm using Visual Studio C# WPF SerialPort class to communicate with an microcontroller using USB Cable and driver.

I want to read input from COM port continuously.

This is my current implementation:

public SerialConnectionHandler()
{
        port = new SerialPort("COM3");
        port.BaudRate = 9600;
        port.Parity = Parity.None;
        port.StopBits = StopBits.One;
        port.Handshake = Handshake.None;
        port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        port.Open();
}

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    String indata = port.ReadLine();
    Debug.WriteLine(indata);

    processInput(inputData);

    if (port.IsOpen) Debug.WriteLine("--Port is Open--");
}

After an unspecified time my output console reports at least 5 thread ends with code 0. This sometimes takes seconds, minutes or even longer.

I could not reproduce the problem.

Port Settings Match.

Datareceived called
--Port is Open--
Datareceived called
--Port is Open--
Datareceived called
--Port is Open--
Der Thread 0xbb4 hat mit Code 0 (0x0) geendet.
Datareceived called
--Port is Open--
Datareceived called
--Port is Open--
Datareceived called
--Port is Open--
Datareceived called
--Port is Open--
Datareceived called
--Port is Open--
Datareceived called

Thread Ends occur randomly, but at one point, a lot of Thread End reports occur. The event won't be triggered from now on anymore.

The port is reported to be opened just before this happens.

--Port is Open--
Datareceived called
--Port is Open--
Datareceived called
--Port is Open--
Der Thread 0x3bc hat mit Code 0 (0x0) geendet.
Der Thread 0x2f54 hat mit Code 0 (0x0) geendet.
Der Thread 0x2ea0 hat mit Code 0 (0x0) geendet.
Der Thread 0x1a6c hat mit Code 0 (0x0) geendet.
Der Thread 0x308 hat mit Code 0 (0x0) geendet.
Der Thread 0x2b0c hat mit Code 0 (0x0) geendet.
Der Thread 0x7fc hat mit Code 0 (0x0) geendet.

Upvotes: 0

Views: 497

Answers (1)

Starwave
Starwave

Reputation: 2404

So I noticed I had the same problem. On one project DataReceived works perfect, as expected, but on another - this problem.

As it turns out, Glorin is right. The The thread 0xc28 has exited with code 0 I am seeing after few seconds of running my app, is because I was keeping all this code in a seperate class USBCommunicationManager, called from my window class (I'm using WPF) like this:

new USBCommunicationManager(this);

I was simply initializing it, not assigning it to any variable, that's why garbage collector later picked it up and ended the serial read thread. Just changing it like this, solved the problem:

USBCommunicationManager usbCommunicationManager;
..
..
usbCommunicationManager = new USBCommunicationManager(this);

Upvotes: 1

Related Questions