0

I have a serial port listener (inputStream) that has a callback (DataReceived). When I connect a delegate to it that updates a GUI element, it works fine, given that I have defined the delegate inside the GUI Form, but when I resize the form, I get an error stating that the call is coming from a different thread. Not sure why this works sometimes.

public partial class Form1: Form { 
  SerialPort inputStream;

  void SomeFunction() {
        inputStream.DataReceived += delegate (object s, SerialDataReceivedEventArgs args) {
            // transfer data from serial port to buffer
            int bytes = inputStream.BytesToRead;
            byte [] data = new byte[bytes];
            inputStream.Read(data, 0, bytes);
            ...
            total_bytes += bytes;
            total_packets++;
            toolStripStatusLabel1.Text = String.Format("{0} Packets {1} Bytes ({2})", total_packets, total_bytes);
        };
    }
  }

So this works fine unless I resize the window. First, I didn't expect it to work, and I'm more confused as why resizing the window breaks it. Is there some way I can add an invoke someplace to make it work?

reza
  • 1,329
  • 2
  • 22
  • 37
  • Why it doesn't work after I can't tell with certainty. If you want to update a GUI component however, you might want to use `Dispatcher.Invoke()(() => { label.Text = "hello"});` instead. – Jeroen Vannevel Mar 14 '14 at 00:43
  • To clarify, it throws an exception sometimes while resizing the window. If I ignore the errors in the debugger, it will continue to work. – reza Mar 15 '14 at 05:27
  • You should probably add your exception message to your post so we know what the problem is. – Jeroen Vannevel Mar 15 '14 at 11:15

0 Answers0