How to: raise and consume events

Source: Internet
Author: User
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            Counter counter = new Counter(new Random().Next(10));            // 4. subscribe event            counter.ThresholdReached += counter_ThresholdReached;            Console.WriteLine("press ‘a‘ key to increase total");            while (Console.ReadKey(true).KeyChar == ‘a‘)            {                Console.WriteLine("adding one");                counter.Add(1);            }        }        static void counter_ThresholdReached(object sender, ThresholdEventArgs e)        {            Console.WriteLine("Threshold " + e.ThresholdNum + "  reached at time "+ e.TimeReached);        }    }    public class Counter    {        int threshold;        int total;        public Counter(int thresholdVal)        {            threshold = thresholdVal;        }        public void Add(int x)                                                                  {            total += x;            // 5. trigger event            if (total > threshold)              {                ThresholdEventArgs args = new ThresholdEventArgs();                args.ThresholdNum = threshold;                args.TimeReached = DateTime.Now;                OnThresholdReached(this, args);            }        }        // 1. define event        public event EventHandler<ThresholdEventArgs> ThresholdReached;        // 2. define OnXXX virtual method        public virtual void OnThresholdReached(object sender, ThresholdEventArgs e)          {            EventHandler<ThresholdEventArgs> handler = ThresholdReached;            if (handler != null)                handler(this, e);        }    }    // 3. define event arguments    public class ThresholdEventArgs : EventArgs    {        public int ThresholdNum { get; set; }        public DateTime TimeReached { get; set; }    }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.