0

I have three classes - my main Form1 partial class, a class handling a state machine called SystemState, and a class dealing with sending/receiving serial data called SerialCommunications. I have separated these this way to keep my code modular, but so both Form1 and SystemState can send serial data through the one instance of SerialCommunications.

I can pass information from my classes to SerialCommunications by having some public methods. My issue is that I would like my instance of SerialCommunications to go back and update the UI on Form1's thread, but I am not entirely sure how to approach this solution. If there is no better approach, how do I allow my class instance to receive an asynchronous serial message (via SerialDataReceivedEventArgs) in one class, and use it to update the UI on another class and thread?

When I had my serial handling as part of Form1's class in a previous iteration of the code, I was able to receive the asynchronous Serial message and update the UI with delegate and Form1.Invoke-related methods, though will admit I didn't quite understand how they worked. I believe similar concepts will work here, but now that this code has moved into a new class, I am unsure how to achieve what I would like. At the very least I know I can't use [class].Invoke anymore, because Form1 would be considered a control, but not the SerialCommunications class.

I apologise for most of this coming from a lack of understanding some fairly simple concepts, but help is appreciated. The most promising leads I've found have been the following two links, but I haven't quite been able to work out how the apply the solutions to my system.

How to update UI from another thread running in another class

Accessing Form's Controls from another class

Community
  • 1
  • 1
clb9355
  • 289
  • 4
  • 16
  • Few points: 1) you don't necessarily have to use `Form1.Invoke`, it can be any control, typically just `this.Invoke` 2) create a special model class to handle communication: methods to `Start`/`Stop`, to `Send` data, this model can create threads and will rise events for things you need (e.g. `IsConnectedChanged`, `DataReceived`, etc.) 3) Your form can subscribe to events and simply check `InvokeRequired` to invoke call to itself (see [this](http://stackoverflow.com/a/12179408/1997232)). 5) Try to do as little as you can in UI thread, use benefits of already existing thread before invoke. – Sinatr Aug 12 '15 at 07:57
  • Thanks for the advice! Going on your note that Invoke can be performed on any control - does this mean I would have to feed a reference to every relevant UI element through to my serial class? Was hoping to avoid that if it's at all possible... doesn't seem clean but if there's no other choice, then it's fine. As for subscribing to events, I was hoping to avoid creating custom events because it's another area I haven't learned yet. I might just have to suck it up and do it. – clb9355 Aug 12 '15 at 08:12

0 Answers0