Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Identifying Event Handlers


When you add an event to a class you actually add metadata that indicates that instances of the class can raise a named event of a specified type. The metadata also indicates the methods that are used to add a delegate to the event, so that the delegate will be called when the event is raised. There is no standard mechanism for a class to indicate that it can handle an event of a particular type. In this article, I will investigate this issue further.

I started thinking about this issue when I saw the new serialization attributes that will appear in version 2.0 of .NET (Whidbey). I won't go into great detail about this—I know that Juval Lowy is preparing an article on this subject (most likely for MSDN Magazine), so I'll leave the details to him. The current version of .NET (v1.1) serialization already allows you to provide a callback using the IDeserializationCallback interface, which has a single method, OnDeserialization. The idea is that once an object has been deserialized, but before it is returned from IFormatter.Deserialize, the object is given an opportunity to perform some more work. The class indicates that it wants to do this work by implementing the IDeserializationCallback interface, so the formatter specifically looks for this interface.

In Whidbey this idea is extended further, but instead of providing new interfaces, the designers have decided to use attributes. If you are an MSDN subscriber you can download the Visual Studio .NET Whidbey "community edition and take a look at these attributes. Basically, these attributes indicate the methods on the object that will be called at points before and after the object is deserialized. So you will have two mechanisms to indicate callback methods: using attributes, or using an interface. It does lack consistency and appears to be a bit of a mess.

Which mechanism is better? Well, I come from a COM background, so I am used to interfaces, so perhaps I am a bit biased. I decided to test the performance of both mechanisms and although the results agree with my prejudices the values still surprised me.

I defined an interface and an attribute:

interface ICallback
{
   void Call();
}
[AttributeUsage(AttributeTargets.Method)]
class CallbackAttribute : Attribute
{
}

Then I defined two classes, one that implemented the interface and another that marked its methods with the attribute. Neither of them did any work, they are just implemented as empty methods.

class InterfaceImpl : ICallback
{
   public void Call() { }
}
class AttributedMethods
{
   [Callback]
   public void Call() { }
} 

Next, I defined a class that had two methods to which an object is passed. The first method tests the object to see if it implements the interface, and if so, it creates a delegate and stores it; the other uses reflection to check all methods to find one that has the appropriate attribute, and again, if it has, a delegate is created and stored.

delegate void NoParameter();
 
class Caller
{
   event NoParameter delegates;
   public void PassInterfaceObject(object o)
   {
      ICallback cb = o as ICallback;
      if (cb != null)
      {
         delegates += new NoParameter(cb.Call);
      }
   }
   public void PassAttributedObject(object o)
   {
      MethodInfo[] methods = o.GetType().GetMethods();
      foreach(MethodInfo method in methods)
      {
         object[] attrs = method.GetCustomAttributes(typeof(CallbackAttribute), false);
         if (attrs.Length != 0)
         {
            delegates += (NoParameter)Delegate.CreateDelegate(
               typeof(NoParameter), o, method.Name);
         }
      }
   }
} 

The interface object method is straightforward. The reflection method is more complicated because it has to check every method for the required attribute, and once it has ascertained that the method has the attribute then the Delegate.CreateDelegate has to be used to create an appropriate delegate.

In my tests I have called each of these methods 1000 times and timed the total. As a comparison, I also measured the amount of time it takes each method to determine that a method does not have the attribute, or the object does not implement the interface. My results for 1000 calls are as follows:

PassInterfaceObject passed InterfaceImpl object: 0.00390s
PassAttributedObject passed AttributedMethods object: 0.07925s
PassInterfaceObject passed AttributedMethods object: 0.00012s
PassAttributedObject passed InterfaceImpl object: 0.03548s

The first point to make is that PassInterfaceObject is very quick to determine that an object does not implement an interface, whereas PassAttributedObject takes almost half its time determining that the object does not have an attributed method. Of course, the main point of this comparison is to compare the two mechanisms with objects that are acceptable, and this shows that the check for an interface and then adding the interface to the event takes almost half the time it takes to search for an attributed method and add that to the event. (Note that PassAttributedObject does continue to check for attributed methods even after it has found one, but when I changed the code to only check for one method it had little effect on the results.)

This analysis shows that the attributed mechanism is poor compared to the interface mechanism in terms of performance. Another argument is code readability, you could argue that it is more readable, and more immediately noticeable, to indicate event handlers with attributes rather than through interfaces. However, C# allows you to use the fully qualified interface name, which makes it more obvious that the method is an interface method. Compare these two amended classes:

class InterfaceImpl : ICallback
{
   public void ICallback.Call() { }
}
class AttributedMethods
{
   [Callback]
   public void Call() { }
} 

I think that it is just as readable to fully qualify the interface method as it is to use an attribute.

In my opinion the interface mechanism of identifying event handlers is better than the attribute mechanism.


Richard Grimes speaks at conferences and writes extensively on .NET, COM, and COM+. He is the author of Developing Applications with Visual Studio .NET (Addison-Wesley, 2002). If you have comments about this topic, Richard can be reached at [email protected].


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.