Plunging into .NET Development

Weblog Pieter Gheysens
Microsoft .NET Development - C# - Enterprise Library - Visual Studio 2005 Team System - Compuware DevPartner - ...

Tuesday, December 27

Event Accessors

What properties mean for accessing private variables, that does Event Accessors for private events. In Visual Studio 2003 Event Accessors can only be used with C#. Luckily in Visual Studio 2005, this technique is available for VB.NET developers as for C# developers.

Event Accessors give you full control about subscribing to events and unsubscribing from events. Like properties you have the opportunity to perform some (business) checks prior to subscribing/unsubscribing. Really interesting if EventHandling is all over the place in your application. Were you already in a situation that certain EventHandling methods were executed way too many times? First of all this can have serious consequences for performance, but this can also result in unexpected behavior of your application. One solution : Event Accessors!

Instead of having a public EventHandler in your publisher class, you must create a private EventHandler, followed by the Event Accessor.

With the keywords add and remove you are able to do some pre- and/or post-processing. In Visual Studio 2003, add and remove are not shown in blue, but they act the same.

In the example below I prevented for example that a particular EventHandling method (value) can only be subscribed once to the MyEvent. The InvocationList (arrayOfDelegates) will be iterated to check if there's an exact match in the already subscribed list for the new EventHandling method (value) that wants to subscribe to the MyEvent. Only if the new method is not yet registered it will be added to the EventHandling list. That will prevent EventHandling methods to execute more than intended and this will always be good for performance!


Post a Comment

Links to this post:

Create a Link

<< Home