
Declaring Event Accessors
In the previous example, the event TestEvent was declared in a manner similar to fields. Like a field, the event is directly available to users of the object, who can modify it. Unlike fields, the only modifications allowed are through the addition assignment (+=) and subtraction assignment (-=) operators.
It is possible to declare an event using event accessors. Event accessors use a syntax very similar to property accessors, using an add keyword and a code block for adding event handlers to the event, and a remove keyword and a code block for removing event handlers to the event. For example:
|
public class EventSource2
{
private TestEventDelegate TestEventHandlers;
public event TestEventDelegate TestEvent
{
add
{
lock (TestEventHandlers)
{
TestEventHandlers += value;
}
}
remove
{
lock (TestEventHandlers)
{
TestEventHandlers -= value;
}
}
}
private void RaiseTestEvent()
{
// Safely invoke an event.
TestEventDelegate temp = TestEventHandlers;
if (temp != null)
{
temp(this, new System.EventArgs());
}
}
}
|
In order to use event accessors, the class raising the event must have a mechanism to store and retrieve handlers. The previous example uses a private delegate field, TestEventHandlers, and the addition and subtraction assignment operators to add and remove handlers from the list. This is very similar to how an event declared without accessors works. When an event receiver uses the addition assignment operator (+=) to add a handler to the event, the add accessor is called, and the new handler is available within the accessor as a local variable named value. When the subtraction assignment operator (-=) is used, the remove accessor is called, and the handler to be removed is available as a local variable named value. Both accessors return void, so any return statement must not return a value.
Subscribing and unsubscribing to an event uses the same syntax regardless of whether event accessors are declared by the class.
Note |
|---|
| The lock statement is used in the previous example to prevent more than one thread from manipulating the event list at the same time. For more information, see Lock Statements and Threading. |
When accessors are used for an event, the class can store the event handlers in any way it chooses. Although the previous example uses a delegate, other mechanisms can be used. For an example, see How to: Use a Hash Table to Store Event Instances.
Events that do not declare accessors are given thread-safe accessors automatically by the C# compiler. Abstract events cannot declare accessors. Static accessors cannot use the this keyword.