class Program
  {
    // 委托原型
    public delegate int DelegateHandler(int i);

    // 目标方法
    static int Test(int i)
    {
      Console.WriteLine("Async Thread:{0}", Thread.CurrentThread.ManagedThreadId);
      Thread.Sleep(5000);
      return ++i;
    }

    // 异步等待模式 :EndInvoke
    static void Async_EndInvoke()
    {
      DelegateHandler dlg = new DelegateHandler(Test);
      IAsyncResult ar = dlg.BeginInvoke(1, null, null);
      int result = dlg.EndInvoke(ar);
      Console.WriteLine(result);
    }

    // 异步等待模式 :WaitHandle.WaitOne
    static void Async_WaitOne()
    {
      DelegateHandler dlg = new DelegateHandler(Test);
      IAsyncResult ar = dlg.BeginInvoke(1, null, null);
      ar.AsyncWaitHandle.WaitOne();
      int result = dlg.EndInvoke(ar);
      Console.WriteLine(result);
    }

    // 异步等待模式 :IsCompleted
    static void Async_IsCompleted()
    {
      DelegateHandler dlg = new DelegateHandler(Test);
      IAsyncResult ar = dlg.BeginInvoke(1, null, null);
      
      while (!ar.IsCompleted) Thread.Sleep(10);

      int result = dlg.EndInvoke(ar);
      Console.WriteLine(result);
    }

    // 异步等待模式 :CallBack
    static void Aysnc_CallBack()
    {
      DelegateHandler dlg = new DelegateHandler(Test);
      dlg.BeginInvoke(1,
        delegate(IAsyncResult ar)
        {
          int result = (ar.AsyncState as DelegateHandler).EndInvoke(ar);
          Console.WriteLine(result);
        }, dlg);
    }

    // 异步等待模式 :CallBack & Timeout
    static void Async_TimeOut()
    {
      DelegateHandler dlg = new DelegateHandler(Test);
      IAsyncResult iar = dlg.BeginInvoke(1,
        delegate(IAsyncResult ar)
        {
          int result = (ar.AsyncState as DelegateHandler).EndInvoke(ar);
          Console.WriteLine(result);
        }, dlg);

      ThreadPool.RegisterWaitForSingleObject(iar.AsyncWaitHandle,
        delegate(object state, bool timeout)
        {
          // 如果没有超时,该回调方法会在目标方法后立即执行。
          // 不管超时与否,该回调方法都会执行,因此要判断timeout参数。
          Console.WriteLine("Timeout:{0}, Thread:{1}", timeout, Thread.CurrentThread.ManagedThreadId);
        }, null, 10000, true);
    }

    static void Main()
    {
      Console.WriteLine("Main Thread:{0}", Thread.CurrentThread.ManagedThreadId);
      Async_TimeOut();

      Console.WriteLine("Press any key to exit...");
      Console.ReadKey(true);
    }
posted on 2008-03-01 15:05  shawnliu  阅读(216)  评论(0编辑  收藏  举报