CIS NET Applications1 Chapter 6 – Events
CIS NET Applications2 Objectives Delegate-based Events.NET event support Practical guides for managing events
CIS NET Applications3 Delegate-Based Events Source or Publisher: an object publishing the event Sink or Subscriber: any party interested in the event Firing: publishing an event Delegate: type-safe method reference
CIS NET Applications4 Delegate-Based Events (cont) Public delegate void NumberChangedEventHandler(int number); Public class MyPublisher { public NumberChangedEventHandler NumberChanged; /* other methods and members */ } Public class MySubscriber public void OnNumberChanged(int number) { string message = “New value is “ + number; MessageBox.Show(message,”MySubscriber”); }} MyPublisher publisher = new MyPublisher(); MySubscriber subscriber1 = new MySubscriber(); //Adding subscriptions Publisher.NumberChanged += new NumberChangedEventHandler (subscriber1.OnNumberChanged); //Firing the event Publisher.NumberChanged(3); //Removing subscriptions Publisher.NumberChanged -= subscriber1.OnNumberChanged; delegate inference Must have Same signature
CIS NET Applications5 Delegate-Based Events (cont) Potential problem with exposing the delegate as a public member Fix: define delegates as an event which only allows the publisher class to fire the event Public delegate void NumberChangedEventHandler(int number); Public class MyPublisher { public event NumberChangedEventHandler NumberChanged; public void FireEvent(int number) { NumberChanged(number) } /* other methods and members */ }
CIS NET Applications6.NET Loosely Coupled Events Can’t subscribe to type of event – only to publisher objects Events can’t be filtered Subscriber must be able to “see” Publisher – i.e., both must be running All “connections” must be done programmically
CIS NET Applications7 Working with.NET Events Defining Delegate Signatures –Target methods should have void return types –Signature should contain publisher’s identity –Use argument container like EventArgs.NET provides the EventHandler delegate: public delegate void EventHandler(object sender, EventArgs eventArgs); Publish events defensively – use try – catch blocks EventsHelper class – can be used to catch all exceptions while publishing to all delegates
CIS NET Applications8 Working with.NET Events (cont) Event Accessors: encapsulates the event member variable Managing large numbers of events: use.NET’s EventHandlerList class –Linear list that stores key/value pairs (event obj, delegate instance) Recommend writing Sink Interfaces –Define interface containing set of events –Subscriber implements interface –Publisher provides two methods, Subscribe() and Unsubscribe(); each uses two parameters, the interface and a way to endicate which events to subscribe to (author shows a way to do this using flags)
CIS NET Applications9 Summary Delegate-based Events.NET event support Practical guides for managing events