2

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.

Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
JonBlumfeld
  • 299
  • 2
  • 5
  • 20

4 Answers4

4

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.

CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
3

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#?

Community
  • 1
  • 1
Tudor
  • 61,523
  • 12
  • 102
  • 142
1

I have an answer:

public delegate void DisplayInfoSentDelegate(byte[] abyBuf);

private void SendThread(_dlg pThis, byte[] abyBuf, int iNumOfBytes)
{
  ...
  pThis.Invoke(new DisplayInfoSentDelegate(DisplayInListBox), new object[] { abyBuf});
}
bhs67
  • 29
  • 4
1

I think it doesn't work, cause within your OnReceived method you are trying to write something into a GUI control (e.g. TextBox).

This is the part that fails and not the receiving of the data itself. If you'd like to access the GUI thread within this method you should call [Invoke()][1] or BeginInvoke() on the desired control and put your code within the given lambda.

For more advanced stuff you could also think about using ReactiveExtensions and the ObserveOn() method.

Oliver
  • 43,366
  • 8
  • 94
  • 151