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?
Aucun commentaire:
Enregistrer un commentaire