如何避免对订阅方法负责

时间:2018-12-25 19:37:10

标签: c# design-patterns .net-4.0

我很惊讶地发现,我的功能良好的方法也对我的失败的订阅方法中的失败负责。我应该如何引发该事件以将所有成功通知给所有订户,同时又将所有职责隔离开?

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) { }

我可以在引发事件时捕获异常,但是并不是所有订阅者都得到通知:

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) { }

我希望发送成功通知,让发送者和每个订阅者都对自己负责。什么是正确的设计?

0 个答案:

没有答案