Recently in of the interview question I was asked a question related to event chaining.
Question
Let's assume there are 4 different subscribers have subscribed to an event. Upon event is triggered, all the event subscribers will be called. In one of event handling methods if there an exception happened, what is the impact of that exception in calling the other subscriber's event handling methods.
Answer
Let's think for a while.
As event handling method will be called sequentially, if there are any exceptions happened in one of the event handling methods, then the subsequent subscriber's event handling method will not be called.
If the same unhandled exceptions traverse up the call stack, then it might end up in application crash.
Let's go over an example
Let' define an event, subscribe to the event and raise the event. Later we will the effect of an exception in one event handling method on other subsequent event subscriber methods.
{
// Define an event in the source object
public event Action<object, EventArgs> MyEvent = null;
static void Main(string[] args)
{
Program program = new Program();
// Suscriber 1
program.MyEvent += Program_MyEvent1;
// Subscriber 2
program.MyEvent += Program_MyEvent2;
// Raise event
program.MyEvent(new object(), new EventArgs());
Console.ReadLine();
}
private static void Program_MyEvent1(object arg1, EventArgs arg2)
{
throw new NotImplementedException();
}
private static void Program_MyEvent2(object arg1, EventArgs arg2)
{
}
}
In the above sample program, the 2nd subscriber will never get notified because there is an unhandled exception happening in the first subscriber event handling method.
No comments:
Post a Comment