0

I was surprised to find out that my well functioning methods are kept responsible for failures in subscribed methods having mine fail too. How should I raise the event to notify all the subscribers of the success while keeping all the responsibility isolated?

public class A
{
    public event EventHandler<EventArgs> Success = null;
    public void DoSomething()
    {
        if (this.Success != null) { this.Success(this, EventArgs.Empty); }
    }
}

A a = new A();
a.Success += (object senderObj, EventArgs arguments) => { throw new Exception(); };

try
{
    a.DoSomething();
    int foo = 0; // will not be reached
}
catch (Exception ex) { }

I can catch the exceptions while raising events, but then not all of the subscribers are notified:

public class A
{
    public event EventHandler<EventArgs> Success = null;
    public void DoSomething()
    {
        if (this.Success != null) { try { this.Success(this, EventArgs.Empty); } catch (Exception ex) { } }
    }
}

A a = new A();
a.Success += (object senderObj, EventArgs arguments) => { MessageBox.Show("ok"); };
a.Success += (object senderObj, EventArgs arguments) => { throw new Exception(); };
a.Success += (object senderObj, EventArgs arguments) => { MessageBox.Show("ok2"); }; // is not reached

try
{
    a.DoSomething();
    int foo = 0; // is now reached
}
catch (Exception ex) { }

I was hoping to send the success notifications and have both the sender and each subscriber responsible for itself. What is the proper design?

Demo
  • 394
  • 1
  • 4
  • 16
  • Summary of [duplicate](https://stackoverflow.com/questions/8744480/exception-management-practices-inside-event-handlers) - if exception are expected you have to manually (https://stackoverflow.com/questions/22841879/loop-over-delegate) fire events and deal with exceptions for each handler separately. – Alexei Levenkov Dec 25 '18 at 20:39
  • @AlexeiLevenkov Thank you. The more I think about this, the further I come to the conclusion that the events are not actually independent events called out to the open, but rather just a syntactic sugar for calling items of a delegate methods collection by the event raising object itself, thus leaving the responsibility rightfully to the caller. Events would have to be raised async and the exception raised in the subscribers would have to bubble up somewhere to the very entry point of the process to be actual independent events. I kinda see how that'd would be a different approach altogether. – Demo Dec 25 '18 at 23:23

0 Answers0