1 using System; 2 3 namespace ConsoleApplication1 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 Counter c = new Counter(new Random().Next(10)); 10 c.ThresholdReached += c_ThresholdReached; 11 12 Console.WriteLine("press 'a' key to increase total"); 13 while (Console.ReadKey(true).KeyChar == 'a') 14 { 15 Console.WriteLine("adding one"); 16 c.Add(1); 17 } 18 } 19 20 static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e) 21 { 22 Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached); 23 Environment.Exit(0); 24 } 25 } 26 27 class Counter 28 { 29 private int threshold; 30 private int total; 31 32 public Counter(int passedThreshold) 33 { 34 threshold = passedThreshold; 35 } 36 37 public void Add(int x) 38 { 39 total += x; 40 if (total >= threshold) 41 { 42 ThresholdReachedEventArgs args = new ThresholdReachedEventArgs(); 43 args.Threshold = threshold; 44 args.TimeReached = DateTime.Now; 45 OnThresholdReached(args); 46 } 47 } 48 49 protected virtual void OnThresholdReached(ThresholdReachedEventArgs e) 50 { 51 EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached; 52 if (handler != null) 53 { 54 handler(this, e); 55 } 56 } 57 58 public event EventHandler<ThresholdReachedEventArgs> ThresholdReached; 59 } 60 61 public class ThresholdReachedEventArgs : EventArgs 62 { 63 public int Threshold { get; set; } 64 public DateTime TimeReached { get; set; } 65 } 66 }