Information Technology Reference
In-Depth Information
Removing Event Handlers
You can remove an event handler from an event by using the -= operator, as shown here.
mc.Elapsed -= ca.TimerHandlerA; // Remove handler A.
For example, in the following code, you remove the event handler for ClassB after the first
two times the event is raised, and then let the program run for another 2 seconds.
...
mc.Elapsed += ca.TimerHandlerA; // Add instance handler A.
mc.Elapsed += ClassB.TimerHandlerB; // Add static handler B.
Thread.Sleep(2250); // Sleep more than 2 seconds.
mc.Elapsed -= ClassB.TimerHandlerB; // Remove static handler B.
Thread.Sleep(2250); // Sleep more than 2 seconds.
This code produces the following output. The first four lines are the result of both handlers
being called twice, in the first two seconds. After you removed the handler for ClassB , only the
handler for the instance of ClassA was called, during the last 2 seconds.
Class A handler called
Class B handler called
Class A handler called
Class B handler called
Class A handler called The event handler for ClassB has been removed.
Class A handler called
Search WWH ::




Custom Search