Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / C#

Facts and Fallacies of Events in C#

Rate me:
Please Sign up or sign in to vote.
4.76/5 (45 votes)
24 Jul 2007CPOL6 min read 92.4K   652   64  
Delegates: how to add them to an event, how they get removed and when that is necessary
//#define NET11			// uncomment this line to get .NET 1.1 compatible code

using System;
using System.Windows.Forms;			// Button

namespace LP_EventHandlerRemoval {
	class Program {
		static void Main(string[] args) {
			EventHandlerRemovalTest test=new EventHandlerRemovalTest();
			Console.WriteLine("LP#EventHandlerRemoval V1.0");
			test.Run();
			Console.Write("Hit ENTER key to terminate ");
			Console.ReadLine();
		}
	}

	public class EventHandlerRemovalTest {
		private int clicks=0;
		private int delegateCount=0;
		private Button btn=new Button();

		public EventHandlerRemovalTest() { }

		public void Run() {
			log("");
			log("Uppercase text logs program actions");
			log("Lowercase text logs results of simulated button clicks");
			log("Everything gets numbered sequentially");
			log("");
			doClick();
			addDelegate();
			doClick();
			addDelegate();
			doClick();
			removeDelegate();
			doClick();
			removeDelegate();
			doClick();
			removeDelegate();
			doClick();
			log("");
			log("Done");
			log("");
			log("Observations:");
			log("  - each ADD DELEGATE adds one delegate");
			log("  - each REMOVE DELEGATE removes one delegate (if any)");
			log("    and does not throw an exception (if none)");
			log("");
		}

		private static void log(string s) {
			if (s.Length!=0) s=DateTime.Now.ToString("ss.fff  ")+s;
			Console.WriteLine(s);
		}

		private void doClick() {
			log("CLICK");
			btn.PerformClick();
		}

		private void addDelegate() {
			log("");
			delegateCount++;
			log("ADD DELEGATE #"+delegateCount);
#if NET11
			btn.Click+=new EventHandler(btn_Click);
#else
			btn.Click+=btn_Click;
#endif
		}

		private void removeDelegate() {
			log("");
			log("REMOVE DELEGATE #"+delegateCount);
			delegateCount--;
			try {
#if NET11
				btn.Click-=new EventHandler(btn_Click);
#else
				btn.Click-=btn_Click;
#endif
			} catch { log("failed to remove handler"); }
		}

		private void btn_Click(object sender, EventArgs e) {
			clicks++;
			log("    got click #"+clicks);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Belgium Belgium
I am an engineer with a background in electronics, software and mathematics.

I develop technical software, both for embedded systems and for desktop equipment. This includes operating systems, communication software, local networks, image processing, machine control, automation, etc.

I have been using all kinds of microcontrollers and microprocessors (Intel 4004/8080/8051/80386/Pentium, Motorola 680x/680x0/ColdFire/PowerPC, Microchip PIC, Altera NIOS, and many more), lots of programming languages (all relevant assemblers, Fortran, Basic, C, Java, C#, and many more), and different operating systems (both proprietary and commercial).

For desktop applications and general development tools I have been using both UNIX systems and Mac/MacOS for many years, but I have switched to x86-based PCs with Windows, Visual Studio and the .NET Framework several years ago.

I specialize in:
- cross-platform development (making software that runs on diverse hardware/OS combinations)
- instruction set simulation
- improving software performance, i.e. making sure the software runs the job at hand in as short a time as possible on the given hardware. This entails algorithm selection, implementation design, accurate measurements, code optimisation, and sometimes implementing virtual machines, applying SIMD technology (such as MMX/SSE), and more.

Comments and Discussions