zoukankan      html  css  js  c++  java
  • Thread Basics using Timer to trigger Event at a specified internals

    1. what's timer
    Timer provides a mechanism for executing a method in at specified intervals.
    the hierarchy can be the following:
    System.Threading.timer;
    System.Timer.timer;
    System.Windows.form.timer;

    2. relevant method about timer.

     public class AsynTest
        {
            private int result;//
    which is get randonly asynchrounousely by method GetResultAsync;
            ManualResetEvent endProcessEvent;

            public AsynTest(ManualResetEvent endprocessevent)
            {
                this.endProcessEvent = endprocessevent;
            }

            int GetResult()
            {
                Random rd = new Random();
                result =(int)(100*rd.Next())%100;
                Console.WriteLine("get value asynchronousely!");
                return result;
            }

            public delegate int GetResultDelegate();

            public void  GetResultAsync(object obj)
            {
                GetResultDelegate grd = new GetResultDelegate(GetResult);
                AsyncCallback cb = new AsyncCallback(this.GetIntergerfromCallBack);
                IAsyncResult ar = grd.BeginInvoke(cb, null);
                Console.WriteLine("result={0}",result);
                if (result%2 == 0)
                    Console.WriteLine("result is an even number");
            }

             //get the result asynchronousely
            
    public void GetIntergerfromCallBack(IAsyncResult ar)
            {
                try
                {
                    GetResultDelegate del = (GetResultDelegate)((AsyncResult)ar).AsyncDelegate;
                    del.EndInvoke(ar);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
               
            }


            static void Main(string[] args)
            {
                System.Threading.Thread.CurrentThread.Name = "MainThread";
               
    ManualResetEvent endProcessEvent = new ManualResetEvent(false);
                AsynTest hiron = new AsynTest(endProcessEvent);
               
    TimerCallback timercallback = new TimerCallback(hiron.GetResultAsync);
                Timer timer = new Timer(timercallback, i, 0,2000);
                //Blocks the current thread until the current waithhandle receives a signal
                endProcessEvent.WaitOne();
            }
    we can see such windows:



  • 相关阅读:
    第01组 团队Git现场编程实战
    第01组 团队项目-需求分析报告
    团队项目-选题报告
    第二次结对编程作业
    第1组 团队展示
    第一次结对编程作业
    第一次博客作业
    2019 SDN上机第1次作业
    第08组 团队项目-需求分析报告
    团队项目-选题报告
  • 原文地址:https://www.cnblogs.com/Winston/p/1140168.html
Copyright © 2011-2022 走看看