gpt4 book ai didi

c# - EventHandler 正确引发事件

转载 作者:太空宇宙 更新时间:2023-11-03 21:09:07 26 4
gpt4 key购买 nike

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

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

关于c# - EventHandler 正确引发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38915687/

26 4 0