Skip to main content
 首页 » 编程设计

c#之EventHandler 正确引发事件

2024年02月05日18落叶无声

我试图更好地了解事件及其处理程序的工作原理,但我不明白为什么在引发事件时通常更倾向于引发与我们的事件本身相同的事件。 更具体地说,当查看 msdn 文档(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; 
} 

我不明白的是为什么“处理程序”是在 OnThresholdReached 函数中创建的,而不是有

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

我们为什么要创建这个“处理程序”?

请您参考如下方法:

考虑这段代码:

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

如果 ThresholdReached 的处理程序在 if (ThresholdReached!= null) 之后但在 ThresholdReached(this, e); 被称为?

获取处理程序的副本可防止这种情况发生,并使事件线程安全。