Events and Callbacks

A callback method is a method that is automatically invoked by a delegate when an operation or activity completes. For example, one of the asynchronous design patterns uses AsyncCallback delegates to specify the code that executes when an asynchronous operation completes. This design pattern is used in the BeginWrite method, which uses a callback to process the results of an asynchronous write operation.

Events are mechanisms similar to callbacks. Events allow user-specified code to execute under specific conditions, usually involving a state change or an activity's start or end. Events are easier to use than callbacks because language syntax and tools provide a uniform coding experience for recognizing and handling events. Also, events are handled by delegates called event handlers that have a well-defined signature pattern. For more information about events, see Event Design.

The following guidelines help ensure that your library design uses events and callbacks according to best practices.

Consider using callbacks to allow users to provide custom code to be executed by the Framework.

Consider using events to allow users to customize the behavior of a framework without the need for the users to understand object orientation.

Do prefer events over plain callbacks as they are more familiar to a broader range of developers and are integrated with Visual Studio statement completion.

Avoid using callbacks in performance-sensitive APIs.

While callbacks and events are easier for many developers to understand and use, they are less desirable than Virtual Members from a performance and memory consumption perspective.

Do understand that by calling a delegate, you will be executing arbitrary code, which might have security, correctness, and compatibility repercussions.

Events and callbacks allow arbitrary code to be executed in the context of the common language runtime (CLR). Your code and security reviews should carefully examine these extensibility points to identify security vulnerabilities.

Portions Copyright 2005 Microsoft Corporation. All rights reserved.

Portions Copyright Addison-Wesley Corporation. All rights reserved.

For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.

See Also

Other Resources

Designing for Extensibility

Design Guidelines for Developing Class Libraries