Bel*_*ius 1 c# events event-handling
我试图更好地了解事件及其处理程序的工作方式,但我不明白为什么在引发事件时通常更喜欢引发相同的事件,即我们的事件本身。更具体地说,在查看 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;
}
Run Code Online (Sandbox Code Playgroud)
我不明白的是为什么在OnThresholdReached函数中创建了“处理程序” ,而不是
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
if (ThresholdReached!= null)
{
ThresholdReached(this, e);
}
}
Run Code Online (Sandbox Code Playgroud)
我们为什么要创建这个“处理程序”?
考虑这个代码:
if (ThresholdReached!= null)
{
ThresholdReached(this, e);
}
Run Code Online (Sandbox Code Playgroud)
如果在ThresholdReached之后删除处理程序if (ThresholdReached!= null),但在ThresholdReached(this, e);调用之前,多线程代码中会发生什么?
获取处理程序的副本可防止这种情况发生并使事件的引发成为线程安全的。
| 归档时间: |
|
| 查看次数: |
856 次 |
| 最近记录: |