简体   繁体   中英

Why is an additional if statement to check if an event is null before invoking it?

I am going through this code below:

public delegate void PersonArrivedEventHandler(string personName, byte[] personId);

    public class SCLib
    {
        public event personArrivedEventHandler personrrived;

        public SCLib()
        {
            // Simulate that the person arrived after 2000 milli-seconds.
            Task.Run(() =>
            {
                System.Threading.Thread.Sleep(2000);
                OnPersonArrived("personName", new byte[] { 0x20, 0x21, 0x22 });
            });
        }

        protected virtual void OnPersonArrived(string smartCardReaderName, byte[] smartCardId)
        {
            if (this.personArrived != null)
            {
                PersonArrived(personName, personId);
            }
        }
    }

But, I don't know what is the significance of this line, if (this.personArrived != null) .

Why is this check done here? Is there any significance of the if statement here? I removed this line and ran the program and everything works as before.

Thanks.

如果class的使用者未订阅该事件,则调用该event将引发异常,因为如果未订阅,则PersonArrived为null。

如果使用未分配处理程序的事件,则该事件将生成一个异常,因为它为null,因此需要在启动该事件之前对其进行检查。

Because it will be null if no delegates are attached to the event. If you try to invoke such a null event you will get the standard NullReferenceException .

'Events' are subscribe by class object using add handler.

SCLibObject.personrrived += new personArrivedEventHandler(somemethod)

If class object is not subscribe the event then you will get NullReferenceException . So before calling events check if it is null or not.

In a multi-threading application you should store the eventhandlers in a local variable before invoking. See this SO answer , this blog post from Eric Lippert and this SO answer for more details.

void SomeEventInvoke(object sender, EventArgs args) {
    EventHandler ev = SomeEvent;
    if (ev != null) ev(sender, args);
}

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