IAsyncResult模式的优点是什么? [英] What are the strengths of the IAsyncResult pattern?

查看:64
本文介绍了IAsyncResult模式的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得许多类(例如 TcpClient UdpClient HttpListener )如果已经被理解和使用起来会容易得多.事件驱动.而且 IAsyncResult 模式非常难以实现,因为它使您进入各种奇怪的用例:

I feel that many classes (e.g. TcpClient, UdpClient, HttpListener) would've been much easier to understand and use if they were event driven. And IAsyncResult pattern is excessively hard to implement because it opens you to all kinds of weird use cases:

  1. 如果调用者连续调用多个Begin方法怎么办?
  2. 如果调用者将Begin方法和常规方法混在一起怎么办?

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

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

编辑:请把讨论重点放在.NET 2.0上,因为这是我必须使用的.

Please focus the discussion on .NET 2.0 as that's what I have to work with.

推荐答案

以此类推.但是,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.

这篇关于IAsyncResult模式的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆