Delegation action <T> against event handler related to deletion
I am looking for architectural advice as well as a deeper understanding of delegates and lambda (in addition to having to fix the real problem!)
We have a code that interacts with the device (scale) through the serial port on the PDA. We connect the view to receive data from the device. Since only one view is โconnectedโ to our scale instance at a time, we used an Action type property to handle the interaction between the scale instance and the view (instead of subscribing to an event). The view then sets this property to lambda, which takes a value from the scale and changes the user interface.
The problem we are currently facing is to remove our view. If the scale is currently sending data (and we are inside the Action handler) when the user closes the view (when we force Dispose when using CF), the application hangs: Action lambda never terminates AND Repairing the scale instance freezes when you try to close SerialPort.
Is there a key difference in how Action is a property in the class that is handled in this situation compared to the event?
Based on the log data, the code is inside the Action lambda (which changes some elements of the user interface) when Dispose is called in the view. They are both in the user interface thread - how can they work at the same time? Didnโt I sleep last night?
Does anyone see here some bad architectural decisions that should be fixed?
Thanks. I can try to get code samples here if the description does not make enough sense.
When not used as an expression tree, lambda is converted to a normal delegate, so this should not be a problem.
But it all sounds like a deadlock / concurrency issue. Instead of closing the serial port directly, use the signal throughout the action of the action handler (which probably runs simultaneously in another thread, check it again) so that you can gracefully wait for it to complete before closing the port.
No - the event is really just a delegate, like Action
They cannot work simultaneously in the same thread. Most likely, you use Disposing in a separate thread or the action handler works in a separate thread. If this occurs in response to the serial port, verify that serial port events occur in the background thread.
There really is not enough information to say what should or should not be changed from an architectural point of view. In doing so, I ask why you are not using events. Indeed, there is no advantage to using an โactionโ versus using an event handler, but the latter seems to be more closely aligned with the mental model and will show your intent more clearly.