简体   繁体   中英

EventHandler raise Event properly

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" ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM