C# Source Code: Tip: Subscribing to events (avoiding duplicate events)
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Tip: Subscribing to events (avoiding duplicate events)
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Tuesday, October 19, 2004
Hits:
1183
Category:
Delegates/Events
Article:
It is common place to subscribe and unsubscribe to an event (eg. in a property set). If you are dynamically subscribing and unsubscribing to events then you should always assume that the event is already being listened to and remove the subscription first "-=", before you subscribe to it using "+=". If you do not do this and the user of your class sets the same property twice you will end up receiving a duplicate event notification. Note, removing the subscription to an event that you are not listening to will not generate an error. See the example console application below: using System; namespace vbUsers.Events { class DuplicateEventsDemo { ///
/// Demonstrates what happens if you don't unsubscribe to an event, /// before subscribing. ///
[STAThread] static void Main(string[] args) { DupEvents dp = new DupEvents(); Console.WriteLine("Subscribing to the same event twice"); dp.testEvent += new EventHandler(dp_testEvent); dp.testEvent += new EventHandler(dp_testEvent); Console.WriteLine(); Console.WriteLine("Raising the event once"); dp.RaiseTestEvent(); Console.WriteLine("Removing one subscription to the event."); // Should do this before adding a dynamic event dp.testEvent -= new EventHandler(dp_testEvent); Console.WriteLine(); Console.WriteLine("Raising the event once"); dp.RaiseTestEvent(); // Pause the application Console.ReadLine(); } private static void dp_testEvent(object sender, EventArgs e) { Console.WriteLine("Received event {0}", DateTime.Now.ToString()); } } public class DupEvents { public event EventHandler testEvent; public void RaiseTestEvent() { if ( testEvent != null ) { testEvent(this, null); } } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet