Visual Basic Concepts

When to Use Events or Call-Backs for Notifications

See Also

The topics "Asynchronous Notifications Using Call-Back Methods" and "Asynchronous Notifications Using Events" demonstrate that call-backs are more work to implement than events. However, you should not base your decision about which to use on the amount of work involved. Call-backs and events represent different approaches to communication, and you should select the approach that best fits your needs.

You can characterize the difference between events and call-backs as follows: An event is like an anonymous broadcast, while a call-back is like a handshake.

The corollary of this is that a component that raises events knows nothing about its clients, while a component that makes call-backs knows a great deal.

Here’s what these things mean to you as a developer:

Note   An additional difference between events and call-back methods is that events cannot have optional arguments, named arguments, or ParamArray arguments.

A component can provide some notifications using call-backs, and some using events. The nature of the notification determines which mechanism should be used. You should use an event to provide a notification when all of the following statements are true:

  1. The notification can be broadcast anonymously.

  2. The order in which clients receive the notification is not important.

  3. There’s no need for the component to get control back until all clients have received the notification.

  4. If the notification involves ByRef arguments, there’s no need for the component to test the values of those arguments after each client receives the notification. The component only needs to know the last value assigned. (You can plan for clients to cooperate in their use of a ByRef argument — for example, once a Cancel argument is set to True, no client changes it — but there’s no way to enforce this.)

  5. The component doesn't need to know about errors that occur in the client.

If any one of the statements above is false, then you should do the extra work necessary to provide the notification using call-back methods.

You may also want to do the extra work to use call-backs when performance is critical. You can get vtable binding with call-back methods by using the Implements statement to add the call-back interface to the client's call-back object. Events are not vtable bound. (This will be much more noticeable with an in-process component that provides events or call-backs.)