.NET异步编程模式(一)

  • .NET异步编程模式(一)已关闭评论
  • 121 次浏览
  • A+
所属分类:.NET技术
摘要

.NET 提供了三种异步编程模型比如有一个同步方法,读取一定数量的数据,存放到给定缓存中,并指定开始偏移量。

.NET 提供了三种异步编程模型

  • TAP - task-based asynchronous pattern
  • APM - asynchronous programming model
  • EAP - event-based asynchronous pattern

模型对比

比如有一个同步方法,读取一定数量的数据,存放到给定缓存中,并指定开始偏移量。

public class MyClass   {       public int Read(byte [] buffer, int offset, int count);   } 

TAP

TAP是基于任务的异步模式,使用单一方法来表示异步操作的启动和完成,是在 .NET Framework 4 中引入的。TAP是推荐的异步编程模型。C#中的 asyncawait 以及 Visual Basic 中 Async 和 Await 关键字添加了对 TAP 的语言支持。

public class MyClass   {       public Task<int> ReadAsync(byte [] buffer, int offset, int count);   } 

EAP

EAP 是基于事件的异步模型,在 .NET Framework 2.0 中引入。EAP 需要一个有 Async 后缀方法和一个或多个事件。EAP不再推荐用于新开发

public class MyClass   {       public void ReadAsync(byte [] buffer, int offset, int count);       public event ReadCompletedEventHandler ReadCompleted;   } 

APM

APM 使用 IAsyncResult 接口提供异步行为的模型。异步方法需要以 Begin 和 End 开始(比如 BeginWrite 和 EndWrite ).APM不再推荐用于新开发

public class MyClass   {       public IAsyncResult BeginRead(           byte [] buffer, int offset, int count,         AsyncCallback callback, object state);       public int EndRead(IAsyncResult asyncResult);   }