Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview Questions: Exception within Event Handler

1) You have 10 Subscribers to an event in your .NET application. Once you invoke the event, do the subscribers get notified synchronously or asynchronously?

2) You have 10 Subscribers to an event in your .NET application. Now one event handler has a bad code and it throws an exception. Do the other nine event handlers still continue?

Thanks,

like image 404
Houman Avatar asked Feb 19 '11 23:02

Houman


1 Answers

You have 10 Subscribers to an event in your application. Once you invoke the event, do the subscribers get notified synchronously or asynchronously?

It depends on how the publisher "invokes" the event. In the typical case (e.g. a C# field-like event), the handlers are just members of the invocation-list of a multicast delegate. Invoking the "event" is equivalent to invoking the backing delegate, which in turn is morally equivalent to invoking each of its individual members sequentially. So once could view an invocation such as:

MyEvent(this, myEventArgs);

as similar to:

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

It's just a sequence of delegate invocations: the subscribers are notified synchronously. Of course, the publisher can choose to invoke the event any way it pleases, so it needn't do it this way - it may well use the thread-pool (QUWI / BeginInvoke) or any other mechanism that produces asynchronous notifications.

You have 10 Subscribers to an event in your application. Now one event handler has a bad code and it throws an exception. Do the other nine event handlers still continue?

Again, it depends. In the typical (aforementioned) case, the answer is no, because exceptions are not being handled on a per-subscriber basis. If a handler throws, the remainder of the "foreach" is abandoned. Of course, there's nothing to stop a publisher from wrapping the invocation of each handler in a try-catch (ignore) block, or use any other mechanism to ensure that all the handlers are invoked.

like image 77
Ani Avatar answered Oct 20 '22 00:10

Ani