Code Snippet for Events

Name: Event
Description: Code snippet for an event and the corresponding On... method
Shortcut: event
Result:

public event EventHandler<EventArgs> EventRaised;

protected virtual void OnEventRaised( EventArgs e )
{
    EventHandler<EventArgs> handler = this.EventRaised;
    if (handler!= null) handler( this, e );
}

Download: Event.snippet

 

(Update 2005–11–23: Changed to make the “On...” method thread safe. Thanks Eric!
D’oh… I even wrote about this in January, but as thread safety wasn’t an issue in any of my code, I went back to the “old pattern” at some point, as it meant less typing. But a code snippet should of course use the correct pattern, right?)

1 Comment

  • You could make the OnEventRaised method thread-safe by changing the code slightly. Otherwise, you run the risk that someone might disconnect from your event between the check for null and the call to the handler.



    protected virtual void OnEventRaised( EventArgs e )

    {

    EventHandler&lt;EventArgs&gt; handler = this.EventRaised;

    if (handler != null)

    handler( this, e );

    }

Comments have been disabled for this content.