Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serial Communication in Background Thread

Quick question concerning communication between arduino boards and a c# winforms application. Basically what I did so far is something like

_serialPort = new SerialPort();
...
_serialPort.Open();
...
_serialPort.DataReceived += OnReceived;
...
private static void OnReceived(object sender, SerialDataReceivedEventArgs c)
{
// Do something
}

This works as long I put this in the Main-Thread of the application. My question is would it be possible to write a class, that does the same as the code above (listening to the communication via serialport) in a background-thread.

like image 340
JonBlumfeld Avatar asked Feb 01 '26 20:02

JonBlumfeld


2 Answers

You probably can, as long as the SerialPort is instantiated and all events and operations happen on the background thread only.

From MSDN:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

So the class is not "Thread Safe" so trying to do anything in a multi-threaded manner is not a good idea.

like image 158
CodingGorilla Avatar answered Feb 03 '26 08:02

CodingGorilla


Starting a new thread to execute that code is not a problem. The problem might arise if you are using some data produced by the thread to update the UI of the application. See this other question on SO: How to update the GUI from another thread in C#?

like image 36
Tudor Avatar answered Feb 03 '26 09:02

Tudor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!