Interview questions: exception in event handler

1) You have 10 event subscribers in your .NET application. As soon as you trigger an event, do subscribers receive a notification synchronously or asynchronously?

2) You have 10 event subscribers in your .NET application. Now one event handler has bad code and throws an exception. Are the other nine event handlers continuing?

Thanks,

+8
c # events exception order
source share
3 answers

You have 10 event subscribers in your application. When you trigger an event, do subscribers receive a notification synchronously or asynchronously?

It depends on how the publisher "triggers" the event. In a typical case (for example, a C # field event), the handlers are simply members of the call list of the multicast delegate. Invoking an β€œevent” is equivalent to invoking a support delegate, which, in turn, is morally equivalent to invoking each of its individual members in sequence. Therefore, once it was possible to call a call, for example:

MyEvent(this, myEventArgs); 

looks like:

 foreach(EventHandler handler in myEventDelegate.GetInvocationList()) handler(this, myEventArgs); 

This is just a sequence of delegate calls: subscribers are notified synchronously . Of course, the publisher can select the event in any way that he likes, so he does not need to do this - he can very well use the thread pool (QUWI / BeginInvoke) or any other mechanism that creates asynchronous notifications.

You have 10 event subscribers in your application. Now one event for the handler has bad code, and it throws an exception. Do nine more event handlers go on?

Again, it depends. In a typical (aforementioned) case, the answer is no , because exceptions are not handled based on each subscriber. If the handler throws, the rest of the "foreach" is abandoned. Of course, there is nothing to stop the publisher from wrapping a call to each handler in a try-catch (ignore) block or using any other mechanism to ensure that all handlers are called.

+19
source share
+4
source share

1) There are no threads. Methods (subscribers) are executed synchronously.

2) It depends. The remaining subscribers will not be executed unless the exception is processed. An exception always stops the code / thread immediately if not processed. This means that if 2 out of 10 subscription methods were performed when an exception occurred, then recovery 8 will not be performed.

Events are simply lists of methods that need to be called .. Net does this behind the scenes.

+2
source share

All Articles