zoukankan      html  css  js  c++  java
  • How to: Raise and Consume Events

    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; }
        }
    }
    
  • 相关阅读:
    Android实现不同Active页面间的跳转
    Android Dialog的整个生命周期
    fragment的基本用法
    使用URLEncoder、URLDecoder进行URL参数的转码与解码
    Android 通过URL获取网络资源
    Dialog向Activity传递数据
    Android 自定义AlertDialog(退出提示框)
    javascript的继承实现
    UVA Graph Coloring
    poj3744高速功率矩阵+可能性DP
  • 原文地址:https://www.cnblogs.com/pengpenghappy/p/3905656.html
Copyright © 2011-2022 走看看