I have developed an event handler that monitors a serial port and parses the bytes returned to get a temperature value. My question is, how do I get this value out to the rest of my programme? The event, and the new value, is inside my event handler, and thus the rest of my solution doesn't know about it. I can't define a method outside to request it, because the rest of the solution doesn't know when new data comes in via the event handler and changes the variable.
I could, I suppose, write it to a new line of a text box on a form somewhere, but this seems to fly in the face of encapsulation.
Is there a sensible way to do this?
It sounds like you should probably expose another event that the rest of your system could subscribe to - TemperatureChanged
, for example. Then you make your event handler (which is attached to the serial port) raise the TemperatureChanged
event when it notices that the temperature has changed.
Your TemperatureChanged
event should have an appropriate type so that the subscriber only has to care about the temperature change, not the raw data that you've interpreted. (It should probably be an EventHandler<TEventArgs>
of some description.)
Another option is that you could just have a Temperature
property, and implement INotifyPropertyChanged
accordingly, raising the event when you change the property in your event handler. This is broadly equivalent, but more general purpose - lots of code (particularly in WPF) knows how to handle INotifyPropertyChanged
.
See more on this question at Stackoverflow