且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IAsyncResult模式的优点是什么?

更新时间:2023-11-20 21:12:04

以此类推.但是,Microsoft已选择在大多数地方使用它.为什么?

And so on. Nevertheless, Microsoft has chosen to use it in most places. Why?

使用 IAsyncResult 的异步模式是框架内使用的原始异步编程模式.它没有什么优势,并且随着时间的推移,复杂性导致新模式的发展.

The async pattern using IAsyncResult was the original asynchronous programming pattern used within the Framework. It has few advantages, and the complexity has led to new patterns being developed over time.

稍后将介绍事件异步编程(EAP)(您在其中具有带有完成事件的开始"方法).这解决了很多复杂性,但是在许多情况下仍然很难使用,因为您仍然必须将逻辑拆分为多种方法.

Event Asynchronous Programming (EAP) was introduced later (where you have a "Begin" method with a completion event). This solved a lot of the complexity, but was still difficult to use in many situations, as you have to split your logic into multiple methods still.

但是,当前的异步模式基于.NET 4的 Task Task< T> 类,并且具有巨大的优势,尤其是与C#5的async/等待支持.幸运的是, TaskFactory.FromAsync 可以是用于轻松地将基于 IAsyncResult 的异步方法对自动包装到 Task< T> 中,以便可以使用新模式..NET 4.5添加了许多框架异步方法的新版本,这些方法返回 Task< T> ,因此新的 async / await 语言支持可以与框架方法一起使用.对于所有异步编程而言,这是首选的方法.

However, the current asynchronous pattern is based around .NET 4's Task and Task<T> class, and provides huge advantages, especially when coupled with C# 5's async/await support. Luckily, TaskFactory.FromAsync can be used to easily wrap an IAsyncResult based asynchronous method pair into a Task<T> automatically, so the new patterns can be used. .NET 4.5 has added new versions of many of the framework's asynchronous methods which return Task<T>, so the new async/await language support can be used with the framework methods. This is the preferred method moving forward for all asynchronous programming.