码迷,mamicode.com
首页 > 其他好文 > 详细

How to: Raise and Consume Events

时间:2014-08-12 00:06:03      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   ar   cti   line   new   res   

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; }
    }
}

How to: Raise and Consume Events,布布扣,bubuko.com

How to: Raise and Consume Events

标签:style   color   io   ar   cti   line   new   res   

原文地址:http://www.cnblogs.com/pengpenghappy/p/3905656.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!