Reputation: 758
I'm trying to better understand how Events and their handler work, but I don't understand why when raising an event it is usually preferred to raise an identical event, that our event itself. To be more specific, when looking at msdn doc (https://msdn.microsoft.com/en-us/library/db0etb8x.aspx) it looks like that :
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;
}
What I don't understand is why "handler" is created in the OnThresholdReached
function, instead of having
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
if (ThresholdReached!= null)
{
ThresholdReached(this, e);
}
}
Why should we create this "handler" ?
Upvotes: 1
Views: 987
Reputation: 117064
Consider this code:
if (ThresholdReached!= null)
{
ThresholdReached(this, e);
}
What would happen in multi-threaded code if the handler for ThresholdReached
is removed after if (ThresholdReached!= null)
, but before ThresholdReached(this, e);
is called?
Taking a copy of the handler prevents this situation from occuring and makes the raising of the event thread-safe.
Upvotes: 5