Background
My program communicates with a device that is usually asynchronous, but can sometimes behave synchronously. I have an event handler that I use for receiving the data asynchronously, then I have a separate event handler that I use when the device is in the synchronous mode. So, when I need to communicate with the device synchronously I will unsubscribe from the asynchronous handler, and subscribe to the synchronous handler as follows:
try
{
// temporarily receive data synchronously
this.myDevice.DataReceived
-= this.AsynchronousHandler;
this.myDevice.DataReceived
+= new SerialDataReceivedEventHandler(this.SynchronousHandler);
// do the communication...
}
finally
{
// go back to receiving asynchronously
this.myDevice.DataReceived
-= this.SynchronousHandler;
this.myDevice.DataReceived
+= new SerialDataReceivedEventHandler(this.AsynchronousHandler);
}
Now, what I am anticipating is that there could be some kind of a problem with subscription/un-subscribing in the finally
clause. Now, I realize that this will be highly unlikely, because the subscription process is the very last statement of the finally
clause... However, let's say that I receive some data while the finally
clause is still being executed and that the event-handler gets called.
Question
Will the event get handled properly even though it was handled while a finally
clause is still being executed? Or, does it not matter at all?