天天看點

[zz]異步操作總結

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()

      ar.AsyncWaitHandle.WaitOne();

    // 異步等待模式 :IsCompleted

    static void Async_IsCompleted()

      while (!ar.IsCompleted) Thread.Sleep(10);

    // 異步等待模式 :CallBack

    static void Aysnc_CallBack()

      dlg.BeginInvoke(1,

        delegate(IAsyncResult ar)

        {

          int result = (ar.AsyncState as DelegateHandler).EndInvoke(ar);

          Console.WriteLine(result);

        }, dlg);

    // 異步等待模式 :CallBack & Timeout

    static void Async_TimeOut()

      IAsyncResult iar = dlg.BeginInvoke(1,

        delegate(IAsyncResult ar)

      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);

繼續閱讀