Delegates & Events
The topic of Delegates and Events came up on Thursday and I made up an example on the spot which I thought rather appropriate and fun besides.
We started with "What is a Delegate" by declaring a delegate and invoking a method through it. The Array.FindAll method works well for a "real world" example for using Delegates, but involves Generics which my audience have not yet learned. Oops, my bad!
To demonstrate the declaration and raising of an event, we implemented our own Timer. We use the System.Threading.Timer but on Tick we apply a bit of logic. If the Tick matches our made-up requirement, our FancyTimer raises its own Tick event:
1 using System;
2 using System.Threading;
3
4 namespace DelegatesAndEvents
5 {
6 public class FancyTimer
7 {
8 Timer ticker;
9
10 public FancyTimer()
11 {
12 this.ticker =
13 new Timer(new TimerCallback(Tick), null, 0, 100);
14 }
15
16 private void Tick(object state)
17 {
18 DateTime now = DateTime.Now;
19 if (now.Second % 2 == 0) // if seconds is an even number
20 {
21 if (EvenTick != null) // null means no subscribers
22 {
23 EvenTick(now); // Raise EvenTick event
24 }
25 }
26 }
27
28 public event EvenTickDelegate EvenTick;
29 public delegate void EvenTickDelegate(DateTime when);
30 }
31 }
The one big, glaring problem with this example is how to run a demo that involves a UI: the Timer's Tick event is not raised on the UI thread. The good news for me is that one of the students already asked about Threading, so I guess it's not a bug, it's a feature! We'll expand this sample to include Form's Invoke method.