?
快捷搜索:  as  test  1111  test aNd 8=8  test++aNd+8=8  as++aNd+8=8  as aNd 8=8

奇跡賭場vip:什么是.Net的異步機制(APM核心IAsyncResult)step 3

?

本文示例源代碼或素材下載

異步的核心: IAsyncResult

Asynchronous Programming Model

全部異步調用歷程中都是環抱IAsyncResult來進行的,大年夜家可以看看上篇文章的例子,BeginXXX 返回這個工具,EndXXX接管這個工具來停止當前異步工具,下面我們來看看IAsyncResult 接口成員/和實現此接口的AsyncResult類成員(此中有些在上篇中已經涉及到)

IAsyncResult接口

1public interface IAsyncResult

2  {

3    WaitHandle AsyncWaitHandle { get; } //壅閉一個線程,直到一個或多個同步工具接管到旌旗燈號

4    Boolean IsCompleted { get; } //判讀當前異步是否完成

5    Object AsyncState { get; } //獲取額外的參數值,請看上一篇文章的Code 4.3

6    Boolean CompletedSynchronously { get; } //險些沒有應用

7  }

AsyncResult類

1  public class AsyncResult : IAsyncResult, IMessageSink

2  {

3    //IAsyncResult 的實現

4    public virtual WaitHandle Asy奇跡賭場vipncWaitHandle { get; }

5    public virtual bool IsCompleted { get; }

6    public virtual object AsyncState { get; }

7    public virtual bool CompletedSynchronously { get; }

8

9    // 其他一些緊張的屬性

10    public bool EndInvokeCalled { get; set; } //查驗是否調用了EndInvoke()

11    public virtual object AsyncDelegate { get; } //獲取原始的委托工具,可查看上一篇文章中的Code 4.1/4.2/5

12  }

留意:基礎上都是只讀屬性

下面我們來看看異步的履行順序,并回首下 IAsyncResult 下各個屬性的利用,假如照樣不認識請看前2篇文章.

Code 1:

1  class Program

2  {

3    static void Main(string[] args)

4    {

5      Console.WriteLine("[(#{1}){0}]:Asynchronous Start", DateTime.Now.ToString(), Thread.CurrentThread.ManagedThreadId);

6

7      AsyncTest test = new AsyncTest();

8      MyThirdAsyncCode.AsyncTest.SalaryEventHandler del = test.YearlySalary;

9      //應用回調函數

10      AsyncCallback callback = new AsyncCallback(OnSalaryCallback);

11      IAsyncResult ar = del.BeginInvoke(100000, 15, 100000, callback, 2000);

12奇跡賭場vip

13      DoAntherJob();

14      Console.ReadLine(); // 讓黑屏等待,不會直接關閉..

15    }

16

17奇跡賭場vip    //開始其他事情.

18    static void DoAntherJob()

19    {

20      Thread.Sleep(1000);/奇跡賭場vip/必要1秒才能完成這個事情,注1

21      Console.WriteLine("[(#{1}){0}]:Do Another Job", DateTime.Now.ToString(), Thread.CurrentThread.ManagedThreadId);

22    }

23

24    static void OnSalaryCallback(IAsyncResult asyncResult)

25    {

26      //經由過程AsyncState 獲取額外的參數.

27      decimal para = (int)asyncResult.AsyncState;

28

29      //經由過程AsyncDelegate 獲取原始的委托工具

30      AsyncResult obj = (AsyncResult)asyncResult;

31      MyThirdAsyncCode.AsyncTest.SalaryEventHandler del =

(MyThirdAsyncCode.AsyncTest.SalaryEventHandler)obj.AsyncDelegate;

32

33      if (asyncResult.IsCompleted)// 判讀是否已經調用完成

34        Console.WriteLine("[(#{1}){0}]:Asynchronous Finished.", DateTime.Now.ToString(), Thread.CurrentThread.ManagedThreadId);

35

36      decimal val = del.EndInvoke(asyncResult);

37

38      Console.WriteLine("[(#{2}){0}]:Output Result:{1}", DateTime.Now.ToString(), val + para, Threa奇跡賭場vipd.CurrentThread.ManagedThreadId);

39    }

40  }

41

42  public class AsyncTest

43  {

44    public delegate decimal SalaryEventHandler(decimal salary, int monthCount, decimal bonus); // 對應YearlySalary措施

45    public decimal YearlySalary(decimal salary, int monthCount, decimal bonus)

46    {

47      //模擬耗時/繁雜的邏輯謀略.

48      Thread.Sleep(3000);//等待3秒,注2

49      return salary * monthCount + bonus;

50    }

51  }

圖1.2

從圖1.2中可以看出,WaitAll會阻礙當火線程(主線程#10),等待所有異步的工具都履行完畢(耗時最長的異步),才開釋當前的線程,WaitAll/WaitAny的重載版本和WaitOne一樣.

3, WaitAny

和WaitAll 基礎上是一樣的.我們可以應用 WaitAny 來指定某個/某幾個委托先等待,改動Code1.2血色部分,應用WaitAny.

Code1.3

//把salayAsyc異步的句柄保存到WaitHandle 工具中

WaitHandle[] handles = { salayAsyc.AsyncWaitHandle };

//阻礙當火線程,直到所有異步調用停止.

WaitHandle.WaitAny(handles);

圖1.3

我們阻礙了DoAntherJob(#10)線程,直到Salary異步調用謀略完成.同樣我們可以巧用這三個措施來改變我們措施履行的順序.

開釋資本

Code2

1static void OnSalaryCallback(IAsyncResult asyncResult)

2    {

3      //經由過程AsyncDelegate 獲取原始的委托工具

4      AsyncResult obj = (AsyncResult)asyncResult;

5      MyThirdAsyncCode.AsyncTest.SalaryEventHandler del =

(MyThirdAsyncCode.AsyncTest.SalaryEventHandler)obj.AsyncDelegate;

6

7      decimal val = del.EndInvoke(asyncResult);

8      asyncResult.AsyncWaitHandle.Close();//顯示的開釋資本

9    }

2步,承襲AsyncResultNoResult工具,并且為他供給返回值和泛型的造訪

Code3.2

1internal class AsyncResult

: AsyncResultNoResult

2  {

3    // Field set when operation completes

4    private TResult m_result = default(TResult);

5

6    public AsyncResult(AsyncCallback asyncCallback, Object state) :

7      base(asyncCallback, state) { }

8

9    public void SetAsCompleted(TResult result,

10      Boolean completedSynchronously)

11    {

12      // Save the asynchronous operation's result

13      m_result = result;

14

15      // Tell the base class that the operation completed

16      // sucessfully (no exception)

17      base.SetAsCompleted(null, completedSynchronously);

18    }

19

20    new public TResult EndInvoke()

21    {

22      base.EndInvoke(); // Wait until operation has completed

23      return m_result; // Return the result (if above didn't throw)

24    }

25  }

3步,模擬長光陰的異步事情

Code3.3

1internal sealed class LongTask

2  {

3    private Int32 m_ms; // Milliseconds;

4

5    public LongTask(Int32 seconds)

6    {

7      m_ms = seconds * 1000;

8    }

9

10    // Synchronous version of time-consuming method

11    public DateTime DoTask()

12    {

13      Thread.Sleep(m_ms); // Simulate time-consuming task

14      return DateTime.Now; // Indicate when task completed

15    }

16

17    // Asynchronous version of time-consuming method (Begin part)

18    public IAsyncResult BeginDoTask(AsyncCallback callback, Object state)

19    {

20      // Create IAsyncResult object identifying the

21      // asynchronous operation

22      AsyncResult ar = new AsyncResult(

23        callback, state);

24

25      // Use a thread pool thread to perform the operation

26      ThreadPool.QueueUserWorkItem(DoTaskHelper, ar);

27

28      return ar; // Return the IAsyncResult to the caller

29    }

30

31    // Asynchronous version of time-consuming method (End part)

32    public DateTime EndDoTask(IAsyncResult asyncResult)

33    {

34      // We know that the IAsyncResult is really an

35      // AsyncResult object

36      AsyncResult ar = (AsyncResult)asyncResult;

37

38      // Wait for operation to complete, then return result or

39      // throw exception

40      return ar.EndInvoke();

41    }

42

43    // Asynchronous version of time-consuming method (private part

44    // to set completion result/exception)

45    private void DoTaskHelper(Object asyncResult)

46    {

47      // We know that it's really an AsyncResult object

48      AsyncResult ar = (AsyncResult)asyncResult;

49      try

50      {

51        // Perform the operation; if sucessful set the result

52        DateTime dt = DoTask();

53        ar.SetAsCompleted(dt, false);

54      }

55      catch (Exception e)

56      {

57        // If operation fails, set the exception

58        ar.SetAsCompleted(e, false);

59      }

60    }

61  }

來自Jeffrey Richter大年夜師更多更具體的異步操作措施, 請查看http://www.wintellect.com/PowerThreading.aspx,對付一些同伙可能看不懂Code3.1-3.3代碼(著實沒什么所謂的),由于涉及到過多的線程常識,這里出于讓你得到更多的更深層次的(異步)熟識為目的,才供給上面代碼.

下一篇章中,我們來看看微軟供給有異步調用的類是若何調用的,并從中我會給出些真實利用情況中的一些小技術,讓你編寫的代碼更壯實更完善.

免責聲明:以上內容源自網絡,版權歸原作者所有,如有侵犯您的原創版權請告知,我們將盡快刪除相關內容。

您可能還會對下面的文章感興趣:

浙江体彩20选5开奖号 哪家理财收益最高 天成配资 广东好彩1开奖结果 黄金股票有哪些 内蒙古快三一定牛形态 国联水产股票 历史上的今天3d开 炒股软件免费下载 北京赛pk10计划 金猎人配资 福建龙岩麻将规则 s赛赛程 股票配资亏损怎么算 河北省快3开奖结果 免费炒股软件排名 p3近100期试机