我试图更好地理解事件及其处理程序是如何工作的,但我不明白为什么在引发事件时通常更倾向于引发一个相同的事件,而不是我们的事件本身。更具体地说,当查看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;
}
我不明白的是为什么在OnThresholdReached
函数中创建"处理程序",而不是具有
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
if (ThresholdReached!= null)
{
ThresholdReached(this, e);
}
}
为什么要创建这个"handler" ?
考虑以下代码:
if (ThresholdReached!= null)
{
ThresholdReached(this, e);
}
在多线程代码中,如果ThresholdReached
的处理程序在if (ThresholdReached!= null)
之后被删除,但在ThresholdReached(this, e);
被调用之前会发生什么?
获取处理程序的副本可以防止这种情况的发生,并使事件的引发是线程安全的。