I have a short events example from .NET 2.0 that I've been using as a reference point for a while. We're now upgrading to 3.5, though, and I'm not clear on the most idiomatic way to do things. How would this simple events example get updated to reflect idioms that are now available in .NET 3.5?
// Args class.
public class TickArgs : EventArgs {
private DateTime TimeNow;
public DateTime Time {
set { TimeNow = value; }
get { return this.TimeNow; }
}
}
// Producer class that generates events.
public class Metronome {
public event TickHandler Tick;
public delegate void TickHandler(Metronome m, TickArgs e);
public void Start() {
while (true) {
System.Threading.Thread.Sleep(3000);
if (Tick != null) {
TickArgs t = new TickArgs();
t.Time = DateTime.Now;
Tick(this, t);
}
}
}
}
// Consumer class that listens for events.
public class Listener {
public void Subscribe(Metronome m) {
m.Tick += new Metronome.TickHandler(HeardIt);
}
private void HeardIt(Metronome m, TickArgs e) {
System.Console.WriteLine("HEARD IT AT {0}",e.Time);
}
}
// Example.
public class Test {
static void Main() {
Metronome m = new Metronome();
Listener l = new Listener();
l.Subscribe(m);
m.Start();
}
}