C#’s event handling takes event handling notification on a twist from Java’s tried-and-true broadcast-subscription mechanism. Using events, disguised in the form of delegates, event subscribers can similarly subscribe to event notification. The event source notifies all event subscribers to calling back on the delegate method they initially sent for subscribing to the event notification list.
- using System;
- using System.Threading;
- namespace TestEvents
- {
- public class WakeupEventArgs : EventArgs
- {
- // Information to be distributed from the event source
- // to each event subscriber (sink)
- private DateTime WakeupDateTime_;
- public WakeupEventArgs(DateTime dt)
- {
- WakeupDateTime_ = dt;
- }
- public string GetWakeupDateTimeStr {
- get { return WakeupDateTime_.ToShortTimeString(); }
- }
- }
- public class Context
- {
- // context object- usually the server application-
- // or any object that controls the notification of events.
- // publicly declare the signature of the event callback method
- // any object that wants to be notified of an event should
- // have a method prepared with just this method signature
- public delegate void WakeupEventHandler(
- Object sender, WakeupEventArgs e);
- // this event is used to maintain a list of observer delegates
- // and raise an event when a poll completes
- private event WakeupEventHandler WakeupEvent;
- public Context()
- {
- }
- public void AddToEventNotificationChain(WakeupEventHandler h)
- {
- WakeupEvent += h;
- }
- public void Sleep()
- {
- try {
- Thread.Sleep(10000);
- WakeupEvent(this,new WakeupEventArgs(DateTime.Now));
- } catch ( Exception )
- {}
- }
- }
- public class Client
- {
- public Client()
- {
- }
- public void SubscribeToContentEvent(Context c)
- {
- c.AddToEventNotificationChain(this.WakeupEventHandler);
- }
- public void WakeupEventHandler(Object sender, WakeupEventArgs e)
- {
- Console.Out.WriteLine(e.GetWakeupDateTimeStr);
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Context ct = new Context();
- Client c = new Client();
- c.SubscribeToContentEvent(ct);
- ct.Sleep();
- // the context object will sleep for 10 seconds,
- // then notify the client
- // the client will print wake up time to console.
- }
- }
- }