public void Add(int x) { total += x; if (total >= threshold) { ThresholdReachedEventArgs args = new ThresholdReachedEventArgs(); args.Threshold = threshold; args.TimeReached = DateTime.Now; OnThresholdReached(args); } }
//Call the delegate ThresholdReached (created below) when called above in the Add function (which calls this when the private field total gets to be //greater than the int value that was passed into this class in the consructor. protected virtual void OnThresholdReached(ThresholdReachedEventArgs e) { /*Thread Safety - Copy the event delegate (creating a multicast Delegate) to a temporary local variable before raising it to avoid the following issue: * Assume we have thread A which is about to raise the event, and it checks and clears the null check and is about to raise the event. * However, before it can do that thread B unsubscribes to the event, which sets the delegate to null. Now, when thread A attempts to raise the event, * this causes the NullReferenceException that we were hoping to avoid! */ //Syntax to use when fomrally declaring the event delegate below //ThresholdReachedEventHandler handler = ThresholdReached; //Syntax to use when not formally declaring the event delegate type but using the shortcut instead EventHandler <ThresholdReachedEventArgs> handler = ThresholdReached; if (handler != null) { handler(this, e); } }
static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e) { Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached); Console.ReadLine(); Environment.Exit(0); }