开发者

Interview Questions: Exception within Event Handler

开发者 https://www.devze.com 2023-02-11 23:16 出处:网络
1) You have 10 Subscribers to an event in your .NET application. Once you invoke the event, do the subscribers get notified synchronously or asynchronous开发者_JS百科ly?

1) You have 10 Subscribers to an event in your .NET application. Once you invoke the event, do the subscribers get notified synchronously or asynchronous开发者_JS百科ly?

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,


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.


  1. Synchronously, by default. It is possible to invoke asynchronously, however.
  2. No, the exception will bubble to to the event source - which will crash. Again, it's possible to change that behavior by invoking each handler separately in a try/catch.


1) No threading. Methods (subscribers) are executed synchronous.

2) It depends. The remaining subscribers will not be executed unless the exception is handled. An exception always halts the code/thread immediately unless handled. This means that if 2 of 10 subscribing methods has been executed when the exception occurs then the remaning 8 will not be executed.

Events are simply lists of methods to be invoked. .Net does this for you behind the scenes.

0

精彩评论

暂无评论...
验证码 换一张
取 消