| title | ms.custom | ms.date | ms.prod | ms.reviewer | ms.suite | ms.technology | ms.tgt_pltfrm | ms.topic | helpviewer_keywords | ms.assetid | caps.latest.revision | author | ms.author | manager | |||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
How to: Raise and Consume Events |
03/30/2017 |
.net |
dotnet-standard |
article |
|
42afade7-3a02-4f2e-868b-95845f302f8f |
13 |
rpetrusha |
ronpet |
wpickett |
How to: Raise and Consume Events
The examples in this topic show how to work with events. They include examples of the xref:System.EventHandler delegate, the xref:System.EventHandler%601 delegate, and a custom delegate, to illustrate events with and without data.
The examples use concepts described in the Events article.
Example
The first example shows how to raise and consume an event that doesn't have data. It contains a class named Counter that has an event named ThresholdReached. This event is raised when a counter value equals or exceeds a threshold value. The xref:System.EventHandler delegate is associated with the event, because no event data is provided.
[!code-csharpEventsOverview#5] [!code-vbEventsOverview#5]
Example
The next example shows how to raise and consume an event that provides data. The xref:System.EventHandler%601 delegate is associated with the event, and an instance of a custom event data object is provided.
[!code-cppEventsOverview#6] [!code-csharpEventsOverview#6] [!code-vbEventsOverview#6]
Example
The next example shows how to declare a delegate for an event. The delegate is named ThresholdReachedEventHandler. This is just an illustration. Typically, you do not have to declare a delegate for an event, because you can use either the xref:System.EventHandler or the xref:System.EventHandler%601 delegate. You should declare a delegate only in rare scenarios, such as making your class available to legacy code that cannot use generics.
[!code-csharpEventsOverview#7] [!code-vbEventsOverview#7]