Callbacks in .NET
Although arguably less convoluted than COM's bi-directional conventions, the subject of bi-directional communication in .NET can often cause confusion. Before jumping into the topic of how COM events are exposed to .NET, it helps to understand the .NET callback mechanisms. This section briefly covers the three main mechanisms for implementing callback behavior in .NET applications:
- Passing an interface instance
- Passing a delegate
- Hooking up to events
Callback Interfaces
In the "callback interfaces" approach, a member can be defined with an interface parameter on which it calls members, perhaps on the same thread or perhaps on a different thread. With this scheme, any client object can simply implement the interface and then pass itself (or an instance of another object implementing the interface) to the member. This is demonstrated with a contrived example in Listing 1.
Listing 1Using an Interface to Provide Callback Functionality in .NET
1: using System; 2: 3: public interface IChatRoomDisplay 4: { 5: void DisplayMessage(string text); 6: void UserJoined(string user); 7: void UserLeft(string user); 8: } 9: 10: public class ConsoleDisplay : IChatRoomDisplay 11: { 12: public void DisplayMessage(string text) 13: { 14: Console.WriteLine("MESSAGE: " + text); 15: } 16: 17: public void UserJoined(string user) 18: { 19: Console.WriteLine("JOINED: " + user); 20: } 21: 22: public void UserLeft(string user) 23: { 24: Console.WriteLine("LEFT: " + user); 25: } 26: } 27: 28: public class ChatRoomClient 29: { 30: public static void Main() 31: { 32: IChatRoomDisplay display = new ConsoleDisplay(); 33: ChatRoomServer server = new ChatRoomServer(); 34: ... 35: server.Run(display); 36: ... 37: } 38: } 39: 40: public class ChatRoomServer 41: { 42: public void Run(IChatRoomDisplay display) 43: { 44: ... 45: // The callback 46: if (display != null) display.DisplayMessage(text); 47: ... 48: } 49: }
Lines 38 define a callback interfaceIChatRoomDisplaythat is used by the Run method in Lines 4248. The ConsoleDisplay class in Lines 1026 implements the three callback methods and acts as the callee when ChatRoomServer.Run calls its DisplayMessage method.
This pattern of callback interfaces is used in several places in the .NET Framework. For example, an object implementing System.Collections.IComparer can be passed to System.Array.Sort or System.Array.BinarySearch for callback purposes. A class type could be used in a method signature for callbacks rather than an interface, but this is usually undesirable because it limits the types of objects that can be passed in.
Delegates
Whereas an interface is a contract for a collection of methods, a delegate is a contract for a single method. Delegates are often referred to as type-safe function pointers because they represent a reference to any method with a signature that matches the delegate definitionwhether it's an instance method or static method (Shared in Visual Basic .NET).
Delegates can be used for callbacks on a method-by-method basis rather than using an interface with potentially several members (such as IChatRoomClient and its three methods). Besides supporting bi-directional communication at the granularity of methods, delegates also enable multicasting of callbacks. This means that multiple delegates can be combined such that what appears to be a single callback to the callback initiator is actually a method invocation on every one of a list of methods.
A delegate is declared like a method with no body plus an extra keyword:
C#:
delegate void DisplayMessage(string text);
Visual Basic .NET:
Delegate Sub DisplayMessage(text As String)
C++:
__delegate DisplayMessage(String* text);
When compiled to metadata, delegates are represented as classes deriving from System.Delegate or the derived System.MulticastDelegate class (for multicast delegates). All delegates defined in C#, Visual Basic .NET, or C++ are emitted as multicast delegates. Because delegates are types just like classes or interfaces, they can appear outside a type definition or inside as a nested type. Listing 2 updates the callback example from Listing 1 using delegates.
Listing 2Using Delegates to Provide Callback Functionality in C#
1: using System; 2: 3: // The delegates 4: public delegate void DisplayMessage(string text); 5: public delegate void UserJoined(string user); 6: public delegate void UserLeft(string user); 7: 8: public class Display 9: { 10: public void ConsoleMessage(string text) 11: { 12: Console.WriteLine("MESSAGE: " + text); 13: } 14: 15: public void AnnoyingMessage(string text) 16: { 17: System.Windows.Forms.MessageBox.Show("MESSAGE: " + text); 18: } 19: } 20: 21: public class ChatRoomClient 22: { 23: public static void Main() 24: { 25: Display display = new Display(); 26: ChatRoomServer server = new ChatRoomServer(); 27: DisplayMessage one = new DisplayMessage(display.ConsoleMessage); 28: DisplayMessage two = new DisplayMessage(display.AnnoyingMessage); 29: DisplayMessage both = one + two; 30: ... 31: server.Run(both); 32: ... 33: } 34: } 35: 36: public class ChatRoomServer 37: { 38: public void Run(DisplayMessage display) 39: { 40: ... 41: // The callback 42: if (display != null) display(text); 43: ... 44: } 45: }
Lines 46 define three delegates replacing the single interface from Listing 1. In this example, the Display class chooses to provide two methods matching only one delegateDisplayMessage. Because an implementation for UserJoined or UserLeft is not required by this version of the ChatRoomServer.Run method, the class doesn't have to bother with them. Lines 27 and 28 create two delegates by passing the function name with a given instance to the delegate's constructor. The C# compiler treats delegate construction specially, hiding the fact that a delegate's constructor requires an instance and a function pointer. In C++, you have to instantiate a delegate as follows:
DisplayMessage* one = new DisplayMessage(display, &Display::ConsoleMessage); DisplayMessage* two = new DisplayMessage(display, &Display::AnnoyingMessage);
Line 29 creates a third delegate by adding the previous two. This provides multicasting behavior so the call to the delegate in Line 42 invokes both the ConsoleMessage and AnnoyingMessage methods (in no guaranteed order). Often, the += and -= operators are used with multicast delegates in order to add/subtract a new delegate from an existing one.
Listing 3 demonstrates the same code that uses delegates from Listing 2, but in Visual Basic .NET rather than C#.
Listing 3Using Delegates to Provide Callback Functionality in Visual Basic .NET
1: Imports System 2: 3: ' The delegates 4: Public Delegate Sub DisplayMessage(ByVal text As String) 5: Public Delegate Sub UserJoined(ByVal user As String) 6: Public Delegate Sub UserLeft(ByVal user As String) 7: 8: Public Class Display 9: Public Sub ConsoleMessage(ByVal text As String) 10: Console.WriteLine("MESSAGE: " & text) 11: End Sub 12: 13: Public Sub AnnoyingMessage(ByVal text As String) 14: System.Windows.Forms.MessageBox.Show("MESSAGE: " & text) 15: End Sub 16: End Class 17: 18: Module ChatRoomClient 19: Sub Main() 20: Dim display As New Display() 21: Dim server As New ChatRoomServer() 22: Dim one As DisplayMessage = AddressOf display.ConsoleMessage 23: Dim two As DisplayMessage = AddressOf display.AnnoyingMessage 24: Dim both As DisplayMessage = both.Combine(one, two) 25: ... 26: server.Run(both) 27: ... 28: End Sub 29: End Module 30: 31: Public Class ChatRoomServer 32: Public Sub Run(ByVal display As DisplayMessage) 33: ... 34: ' The callback 35: If (Not display Is Nothing) Then display(text) 36: ... 37: End Sub 38: End Class
Lines 46 define the three delegates, and Lines 816 contain the Display class with two methods that match the signature of DisplayMessage. Lines 22 and 23 create two delegates by simply using the AddressOf keyword before the name of each method. Lines 22 and 23 could have been replaced with the following longer syntax:
Dim one As DisplayMessage = _ New DisplayMessage(AddressOf display.ConsoleMessage) Dim two As DisplayMessage = _ New DisplayMessage(AddressOf display.AnnoyingMessage)
but the shorter version used in the listing is preferred.
Line 24 creates the both delegate by combining the previous two. Visual Basic .NET doesn't support overloaded operators (such as + used in Listing 2), but calling Delegate.Combine has the same effect as adding two delegates in C#. Similarly, calling Delegate.Remove has the same effect as subtracting one delegate from another in C#.
Events
Events are a layer of abstraction over multicast delegates. Whereas delegates are types, events are first class members of types just like methods, properties, and fields. An event member is defined with a multicast delegate type, representing the "type" of event, or the signature that any handlers of it must have, for example:
C#:
// The delegate public delegate void DisplayMessageEventHandler(string text); // The event public event DisplayMessageEventHandler DisplayMessage;
Visual Basic .NET:
' The delegate Public Delegate Sub DisplayMessageEventHandler(text As String) ' The event Public Event DisplayMessage As DisplayMessageEventHandler
C++:
// The delegate public: __delegate DisplayMessageEventHandler(String* text); // The event public: __event DisplayMessageEventHandler* DisplayMessage;
By convention, delegates representing event handler signatures are given an EventHandler suffix. Visual Basic .NET further simplifies event definitions by enabling you to specify a delegate signature directly in the event definition:
Public Event DisplayMessage(text As String)
In this case, the compiler emits a delegate with the name DisplayMessageEventHandler, nested in the class containing the event.
Just as a property is typically just an abstraction over a private field of the same type with get and/or set accessors, an event, by default, is an abstraction over a private field of the same delegate type with two accessors called add and remove. These two accessor methods expose the delegate's Combine (+) and Remove (-) functionality, respectively, and nothing else.
A consequence of the event's corresponding delegate field being private is that it can only be invokedand therefore the event can only be raisedby the class defining the event, even if the event member is public. This is the reason classes with events often define protected OnEventName methods that raise an event, so derived classes can raise them too.
FAQ: Why would I define a .NET class with events instead of simply using delegates?
Encapsulation is the reason to use events rather than only delegates in .NET applications. Because the only delegate functionality exposed to other classes is adding and removing delegates to the invocation list, the user of an event cannot reassign the delegate field to another instance and thereby disconnect any other event handlers hooked up to the delegate. For a Windows Form, for example, a C# client is prevented from incorrectly doing the following:
// Anyone else listening to the Resize event is disconnected myForm.Resize = new EventHandler(Resize);
and must do the following instead:
myForm.Resize += new EventHandler(Resize);
Another good reason to use events is so clients can take advantage of built-in support in the Visual Studio .NET IDE. For example, events of Windows Forms controls can be exposed in the property and event browser for easy event handler hookup.
An interesting difference between defining events and defining properties is that an event's accessors and the private field being used by the accessors are all emitted by default in C# and Visual Basic .NET. In C#, you can opt to explicitly define these accessors in case you want to implement the event in an alternative way, but the default behavior is almost always sufficient. To get a clear picture of what an event definition really means, here's how you could define everything explicitly in C# and get the same behavior as the DisplayMessage event definitions shown previously:
// Private delegate field private DisplayMessageEventHandler displayMessage; // Public event with explicit add/remove accessors public event DisplayMessageEventHandler DisplayMessage { [MethodImpl(MethodImplOptions.Synchronized)] add { displayMessage += value; } [MethodImpl(MethodImplOptions.Synchronized)] remove { displayMessage -= value; } }
The MethodImplAttribute pseudo-custom attribute is used with the Synchronized value to ensure that multiple threads can't execute these accessors simultaneously.
Listing 4 continues the example from the previous three listings, but this time using events instead of callback interfaces or just delegates.
Listing 4Using Events to Provide Callback Functionality in C#
1: using System; 2: 3: // The delegates 4: public delegate void DisplayMessageEventHandler(string text); 5: public delegate void UserJoinedEventHandler(string user); 6: public delegate void UserLeftEventHandler(string user); 7: 8: public class Display 9: { 10: public void ConsoleMessage(string text) 11: { 12: Console.WriteLine("MESSAGE: " + text); 13: } 14: 15: public void AnnoyingMessage(string text) 16: { 17: System.Windows.Forms.MessageBox.Show("MESSAGE: " + text); 18: } 19: } 20: 21: public class ChatRoomClient 22: { 23: public static void Main() 24: { 25: Display display = new Display(); 26: ChatRoomServer server = new ChatRoomServer(); 27: server.DisplayMessage += new 28: DisplayMessageEventHandler(display.ConsoleMessage); 29: server.DisplayMessage += new 30: DisplayMessageEventHandler(display.AnnoyingMessage); 31: ... 32: server.Run(); 33: ... 34: server.DisplayMessage -= new 35: DisplayMessageEventHandler(display.ConsoleMessage); 36: server.DisplayMessage -= new 37: DisplayMessageEventHandler(display.AnnoyingMessage); 38: } 39: } 40: 41: public class ChatRoomServer 42: { 43: // The events 44: public event DisplayMessageEventHandler DisplayMessage; 45: public event UserJoinedEventHandler UserJoined; 46: public event UserLeftEventHandler UserLeft; 47: 48: public void Run() 49: { 50: ... 51: // The callback 52: if (DisplayMessage != null) DisplayMessage(text); 53: ... 54: } 55: }
This listing starts the same as Listing 2, but with the delegates renamed with an EventHandler suffix. ChatRoomServer now has three event members defined in Lines 4446, each one using one of the three delegate types. ChatRoomClient adds two delegates to the DisplayMessage event (Lines 2730) and removes them when it's finished listening to the events (Lines 3437). Line 52, by invoking the delegate, causes the event to be raised so both ConsoleMessage and AnnoyingMessage are executed.
FAQ: What do I use on the right side of the -= operator when unhooking an event handler? How could subtracting a new delegate instance possibly unhook the instance that was added?
Unhooking an event handler is an odd-looking operation because a new delegate instance is usually what gets subtracted rather than the delegate instance that was originally added. For example:
// Hook up the event handler server.DisplayMessage += new DisplayMessageEventHandler(display.ConsoleMessage); ... // Unhook the event handler server.DisplayMessage -= new DisplayMessageEventHandler(display.ConsoleMessage);
It turns out that the implementation of Delegate.Add and Delegate.Remove disregards delegate instances; all that's important is the object instance and function passed to a delegate's constructor. Therefore, it's not necessary to store a delegate instance you've added in order to remove it later, and the delegate subtraction code in Listing 4 is correct.
In Visual Basic .NET, hooking and unhooking an event handler to an event is done using AddHandler and RemoveHandler statements, respectively, rather than += and -=. Raising an event must be done with a RaiseEvent statement. Listing 5 demonstrates this by updating Listing 4 to Visual Basic .NET.
Listing 5Using Events to Provide Callback Functionality in Visual Basic .NET
1: Imports System 2: 3: Public Class Display 4: Public Sub ConsoleMessage(ByVal text As String) 5: Console.WriteLine("MESSAGE: " & text) 6: End Sub 7: 8: Public Sub AnnoyingMessage(ByVal text As String) 9: System.Windows.Forms.MessageBox.Show("MESSAGE: " & text) 10: End Sub 11: End Class 12: 13: Module ChatRoomClient 14: Sub Main() 15: Dim display As New Display() 16: Dim server As New ChatRoomServer() 17: AddHandler server.DisplayMessage, AddressOf display.ConsoleMessage 18: AddHandler server.DisplayMessage, AddressOf display.AnnoyingMessage 19: ... 20: server.Run() 21: ... 22: RemoveHandler server.DisplayMessage, AddressOf display.ConsoleMessage 23: RemoveHandler server.DisplayMessage, AddressOf display.AnnoyingMessage 24: End Sub 25: End Module 26: 27: Public Class ChatRoomServer 28: Public Event DisplayMessage(ByVal text As String) 29: Public Event UserJoined(ByVal user As String) 30: Public Event UserLeft(ByVal user As String) 31: 32: Public Sub Run() 33: ... 34: ' The callback 35: RaiseEvent DisplayMessage(text) 36: ... 37: End Sub 38: End Class
The combination of delegate-less event definitions in Lines 2830 and delegate-less event hookup using AddHandler and RemoveHandler in Lines 1718 and 2223 means that Visual Basic .NET programmers often don't need to be aware of the existence of delegates to use events. The compiler hides all of the underlying delegate details. The RaiseEvent statement in Line 35 handles the null check before invoking the event's delegate, which had to be performed explicitly in C#. So if the DisplayMessage event had no handlers attached, Line 35 would have no effect.
As with Visual Basic 6, Visual Basic .NET enables the use of a WithEvents keyword to make the use of events even easier than in Listing 5. Listing 6 demonstrates how to use WithEvents in Visual Basic .NET.
Listing 6Using the WithEvents Shortcut in Visual Basic .NET
1: Imports System 2: 3: Module ChatRoomClient 4: Dim WithEvents server As New ChatRoomServer() 5: 6: Sub Main() 7: ... 8: server.Run() 9: ... 10: End Sub 11: 12: Public Sub ConsoleMessage(ByVal text As String) _ 13: Handles server.DisplayMessage 14: Console.WriteLine("MESSAGE: " & text) 15: End Sub 16: 17: Public Sub AnnoyingMessage(ByVal text As String) _ 18: Handles server.DisplayMessage 19: System.Windows.Forms.MessageBox.Show("MESSAGE: " & text) 20: End Sub 21: End Module 22: 23: Public Class ChatRoomServer 24: Public Event DisplayMessage(ByVal text As String) 25: Public Event UserJoined(ByVal user As String) 26: Public Event UserLeft(ByVal user As String) 27: 28: Public Sub Run() 29: ... 30: ' The callback 31: RaiseEvent DisplayMessage(text) 32: ... 33: End Sub 34: End Class
When you declare a class or module variable using WithEvents (Line 4), any of the class's or module's event handler methods are automatically added and removed to the instance when appropriate. Event handler methods are identified with the Handles keyword, seen in Lines 13 and 18. The Handles keyword in Line 13 states that the ConsoleMessage method is an event handler for the server object's DisplayMessage event. Similarly, the Handles keyword in Line 18 states that AnnoyingMessage is also an event handler for the server object's DisplayMessage event. The appropriate AddHandler and RemoveHandler functionality is handled automatically by the compiler.