Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why assign a handler to an event before calling it?

Tags:

c#

events

Basically, I've seen this used all to often:

    public event MyEventHandler MyEvent;

    private void SomeFunction()
    {
        MyEventHandler handler = this.MyEvent;

        if (handler != null)
        {
            handler(this, new MyEventArgs());
        }
    }

When it could just as easily be done like so:

    public event MyEventHandler MyEvent;

    private void SomeFunction()
    {
        if (MyEvent != null)
        {
            MyEvent(this, new MyEventArgs());
        }
    }

So, am I missing something? Is there some reason people assign the event to a handler, then raise the handler instead of the event itself? Is it just "best practice"?

like image 415
michael Avatar asked Feb 28 '11 20:02

michael


People also ask

When would you use an event handler?

Use the EventHandler delegate for all events that don't include event data. Use the EventHandler<TEventArgs> delegate for events that include data about the event. These delegates have no return type value and take two parameters (an object for the source of the event and an object for event data).

What is the purpose of the event handlers in the JavaScript?

JavaScript Event Handlers Event handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.

What does an event handler do?

In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.

Which is the best place to subscribe event handler to an event?

To subscribe to events by using the Visual Studio IDEOn top of the Properties window, click the Events icon. Double-click the event that you want to create, for example the Load event. Visual C# creates an empty event handler method and adds it to your code. Alternatively you can add the code manually in Code view.


1 Answers

The assignment to a local variable ensures that if the event gets unregistered between the if and the actual invocation, the invocation list will not be null (since the variable will have a copy of the original invocation list).

This can easily happen in multithreaded code, where between checking for a null and firing the event it may be unregistered by another thread.

See this SO question and answers.

like image 86
Oded Avatar answered Nov 28 '22 07:11

Oded