程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#基礎學習 —— 異步編程篇 (一)(3)

C#基礎學習 —— 異步編程篇 (一)(3)

編輯:關於C語言

首先是 Begin 之後直接調用 End 方法,當然中間也可以做其他的操作

class AsyncTest
  {
    static void Main(string[] args)
    {
      AsyncDemo demo = new AsyncDemo("jiangnii");
      // Execute begin method
      IAsyncResult ar = demo.BeginRun(null, null);
      // You can do other things here
      // Use end method to block thread until the Operation is complete
      string demoName = demo.EndRun(ar);
      Console.WriteLine(demoName);
    }
  }

也可以用 IAsyncResult的 AsyncWaitHandle屬性,我在這裡設置為1秒超時

class AsyncTest
  {
    static void Main(string[] args)
    {
      AsyncDemo demo = new AsyncDemo("jiangnii");
      // Execute begin method
      IAsyncResult ar = demo.BeginRun(null, null);
      // You can do other things here
      // Use AsyncWaitHandle.WaitOne method to block thread for 1 second at most
      ar.AsyncWaitHandle.WaitOne(1000, false);
      if (ar.IsCompleted)
      {
        // Still need use end method to get result, but this time it will return immediately
        string demoName = demo.EndRun(ar);
        Console.WriteLine(demoName);
      }
      else
      {
        Console.WriteLine("Sorry, can't get demoName, the time is over");
      }
    }
  }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved