Code snippet for event handler

Code snippets are pretty neat. Here's the first one I've created. It sets up a custom event and a handling routine. To use it, you'll need to download the .snippet file because uploading the code into the blog proved to be too much of a pain.

You can import the snippet with Tools->Manage Code snippets, or just put the file in C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C#

Print | posted @ Friday, January 27, 2006 11:44 AM

Comments on this entry:

Gravatar # re: Code snippet for event handler
by Josh Einstein at 6/24/2006 11:12 AM

Two tips:

1) The way you're using add/remove can just be omitted. Unless you're using collections to minimize the number of fields on a type that raises lots of events, there is no need to use the add/remove syntax as C# will compile pretty much the exact same thing for you.

2) In your OnEventName method, you should implement some sort of locking to ensure that in between your check if it's null or not and the time you actually raise the event, the event handlers don't change.

lock (__eventSyncObject) {
if ( MyEvent != null )
MyEvent(this, EventArgs.Empty);
}

Okay enough comments from me today. :)
Gravatar # re: Code snippet for event handler
by Josh Einstein at 6/24/2006 11:14 AM

Oops I'm sorry I just woke up. A better way of doing that without the lock is:

EventHandler myEvent = MyEvent;
if ( myEvent != null )
myEvent(this, EventArgs.Empty);

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 5 and 6 and type the answer here: