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:



posted on 2008-04-07 12:19  飞天舞者  阅读(292)  评论(0编辑  收藏  举报

导航

For more information about me, feel free email to me winston.he@hotmail.com