-1

This question has been asked before but without an answer. I am in the same boat and would like to try my luck again. It seems to be quite fundamental.

Say, I have two events, one event is "Certain Key pressed", the other event is "Data Arrived". I am handling "Data Arrived" event in its event handler to process the data, I want to do something special when the "Certain Key Pressed" event is fired.

One way to handle this is to have some kind of flag, the flag is set in the "Certain Key Pressed" event handler. And the flag is checked in the "Data Arrived" event handler.

I am wondering if there is a more elegant or standard way of handling situations when two or more events have to be fired for an action to occur.

Thanks!!!

Frank
  • 13
  • 3

1 Answers1

0

If you are using winforms, it is important to note that the form events (like Click events) never interrupt each other. Now it depends whether your data processing happens in the same thread (the UI thread) or not. E.g., if you start processing the data in another Click event, and don't start another task or use async-await, then the DataArrived event will occur in the UI thread as well. In this case these event handlers will strictly be called in a sequential manner. The flag approach will work well.

Otherwise see: How to raise cross thread event. With multi-threading, you must take care to protect code that tests and changes the flags (e.g. with lock statement (C# reference)).

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • Thanks @Olivier for the suggestion. I accepted your answer. Currently, I just stick to the flag approach and it works for now. – Frank Jun 12 '20 at 18:16