?
快捷搜索:  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

?

长沙转转麻将必胜口诀 www.fv7j.com.cn 本文示例源代码或素材下载

异步的核心: 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代码(着实没什么所谓的),由于涉及到过多的线程常识,这里出于让你得到更多的更深层次的(异步)熟识为目的,才供给上面代码.

下一篇章中,我们来看看微软供给有异步调用的类是若何调用的,并从中我会给出些真实利用情况中的一些小技术,让你编写的代码更壮实更完善.

免责声明:以上内容源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

您可能还会对下面的文章感兴趣: