Checking if the handler != null vs Checking if the event != null in C# [duplicate]

北慕城南 提交于 2019-12-12 12:40:52

问题


I have seen various coding styles to fire events in C#. The first style consisting of the following:

-an event handler

    public delegate void NumberReachedEventHandler(object sender, 
    NumberReachedEventArgs e);

-an event

    public event NumberReachedEventHandler NumberReached;

-and the method to fire the event

    protected virtual void OnNumberReached(NumberReachedEventArgs e)
    {
        if(NumberReached != null)
        {
            NumberReached(this, e);
        }
    }

The second style however, has a different method to fire the event:

    protected virtual void OnNumberReached(NumberReachedEventArgs e)
    {
        NumberReachedEventHandler handler = NumberReached;
        if(handler != null)
        {
            handler(this, e);
        }
    }

To me, it appears that one style checks if the "event" is null and the second style checks if the delegate is null. However, my understanding is that an event is just an instance of a delegate, so I am wondering if there are any advantages to either way of writing the code. If so, please explain. Thanks in advance.


回答1:


Both are checking to see if the delegate associated with the event is null.

The purpose of storage into the local is to prevent a TOCTOU-style race in multithreaded code.

It is important to note that using a local only eliminates one of two potential races. See my 2009 article on the subject for details: http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx

and also this question:

C# Events and Thread Safety




回答2:


From what I understand of this answer, the first is not thread-safe whereas the second is.

protected virtual void OnNumberReached(NumberReachedEventArgs e)
{
    //If number reached is changed from after this check
    if(NumberReached != null)
    {
        //and between this call, it could still result in a
        //NullReferenceException
        NumberReached(this, e);
    }
}


来源:https://stackoverflow.com/questions/18027063/checking-if-the-handler-null-vs-checking-if-the-event-null-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!