0

I'm trying to raise an event from my worker thread in the SerialPort.DataReceived event in the main thread.

Background: I have a device connected that can send data by itself to the serial port of my PC. I need to recognize this data and when a telegram is completed, pass it to the UI thread to e.g. show received values. Because the data can arrive spontaneously I used the DataReceived Event of the SerialPort class.

The DataReceived Event creates its own background thread, this I know and this is my problem. When the telegram is complete, I raise an event on the open form of the application e.g. to update a certain text field. The problem is, this event raising is done in the worker thread of the SerialPort received Event.

Is there a way to raise this event on the main UI thread?

C. Bismark
  • 11
  • 1
  • 3
  • If you have a reference to a `Control`, or a derived class, you can use `Control.Invoke`, or `Control.BeginInvoke` to execute a delegate on that control's thread, which will be the UI thread. More details can be found [here](https://stackoverflow.com/questions/661561/how-do-i-update-the-gui-from-another-thread?rq=1). – Bradley Uffner May 22 '19 at 10:34
  • Hi Robin,this thread actually answered my question with the second answer in there. I'm passing the MainForm which contains all my user Controls to the class that is doing the serial Port receiving and invoking on this Control to pass the data back to the UI thread. – C. Bismark May 22 '19 at 11:34

1 Answers1

0

I was able to achieve something similar by doing the following:

In the MainWindow class, adding the following:

    internal static MainWindow _MainWindow; 

    internal string SerialData
    {
        get => SerialDataTextBox.Content.ToString();
        set { this.Dispatcher.Invoke((() => { SerialDataTextBox.Content = value; })); }
    }

In the class that contained my event handler/update methods adding the following:

    private string _convertedSerialData;
    public string ConvertedSerialData
    {
        get => _convertedSerialData;
        set
        {
            _convertedSerialData = value;
            MainWindow._MainWindow.SerialData= value == null ? "" : value;
        }
    }

Then, inside your event handler, update the ConvertedSerialData field, and it should then propagate to your UI.

Propagating
  • 130
  • 1
  • 13