EventHandler正确地提升事件

时间:2016-08-12 10:25:27

标签: c# events event-handling

我试图更好地了解事件及其处理程序的工作原理,但我不明白为什么在举办活动时通常会优先提出相同的事件,即我们的事件本身。 更具体地说,在查看msdn doc(https://msdn.microsoft.com/en-us/library/db0etb8x.aspx)时,它看起来像是:

class Counter
{
    private int threshold;
    private int total;

    public Counter(int passedThreshold)
    {
        threshold = passedThreshold;
    }

    public void Add(int x)
    {
        total += x;
        if (total >= threshold)
        {
            ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
            args.Threshold = threshold;
            args.TimeReached = DateTime.Now;
            OnThresholdReached(args);
        }
    }

    protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
    {
        EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
}

我不明白为什么&#34;处理程序&#34;是在OnThresholdReached函数中创建的,而不是

protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
    {
        if (ThresholdReached!= null)
        {
            ThresholdReached(this, e);
        }
    }

我们为什么要创建这个&#34;处理程序&#34; ?

1 个答案:

答案 0 :(得分:4)

考虑以下代码:

    if (ThresholdReached!= null)
    {
        ThresholdReached(this, e);
    }

如果在ThresholdReached之后但在调用if (ThresholdReached!= null)之前删除ThresholdReached(this, e);的处理程序,多线程代码会发生什么?

获取处理程序的副本可以防止出现这种情况,并使事件的引发成为线程安全的。