Asynchronous Programming Patterns
Asynchronous Programming Patterns
The .NET Framework provides three patterns for performing asynchronous operations:
1.Asynchronous Programming Model (APM) pattern (also called the IAsyncResult pattern), where asynchronous operations require Begin and End methods (for example, BeginWrite and EndWrite for asynchronous write operations). This pattern is no longer recommended for new development. For more information, see Asynchronous Programming Model (APM).
2.Event-based Asynchronous Pattern (EAP), which requires a method that has the Async suffix, and also requires one or more events, event handler delegate types, and EventArg-derived types. EAP was introduced in the .NET Framework 2.0. It is no longer recommended for new development. For more information, see Event-based Asynchronous Pattern (EAP).
3.Task-based Asynchronous Pattern (TAP), which uses a single method to represent the initiation and completion of an asynchronous operation. TAP was introduced in the .NET Framework 4 and is the recommended approach to asynchronous programming in the .NET Framework. The async and await keywords in C# and the Async and Await operators in Visual Basic Language add language support for TAP. For more information, see Task-based Asynchronous Pattern (TAP).
比较三种异步编程模式
For a quick comparison of how the three patterns model asynchronous operations, consider a Read method that reads a specified amount of data into a provided buffer starting at a specified offset:
class MyClass { /// <summary> /// a Read method that reads a specified amount of data into a provided buffer starting at a specified offset /// 从buffer字节数组中的第offset位置开始,向后读取count个字节 /// </summary> /// <param name="buffer">源数组数组</param> /// <param name="offfset">读取的起始位置(从0开始的偏移量)</param> /// <param name="count">读取几个字节</param> /// <returns></returns> public int Read(byte[] buffer, int offfset, int count) { return 0; } }
APM
abstract class APM { //public delegate void AsyncCallback(IAsyncResult ar); //AsyncCallback是委托 public abstract IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callBack, object state); public abstract int EndRead(IAsyncResult asyncResult); }
EAP
public delegate void ReadCompletedEventHandler(); abstract class EAP { public abstract void ReadAsync(byte[] buffer, int offset, int count); public event ReadCompletedEventHandler ReadCompleted;//ReadCompletedEventHandler }
TAP
abstract class TAP { public abstract Task<int> ReadAstnc(byte[] buffer, int offset, int count); }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了