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:



  • 相关阅读:
    关于字符串转义的代码
    JAVA发布aar文件
    apache虚拟主机配置HTTPS
    font-face跨域办法
    Javascript数组方法(译)
    Python动态生成变量
    给AOP的after函数使用原函数局部变量
    stopImmediatePropagation的应用
    IE9或以上的浏览器flash值为空时,导致domready不触发
    html写法对gzip压缩率的影响
  • 原文地址:https://www.cnblogs.com/Winston/p/1140168.html
Copyright © 2011-2022 走看看