سؤال

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. What if caller calls multiple Begin methods in a row?
  2. What if caller mixes Begin and regular methods?

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

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

هل كانت مفيدة؟

المحلول

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

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.

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.

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.

نصائح أخرى

This pattern doesn't have many strengths.

In .Net 1.0, before generics and lambda expressions, this was the only asynchronous pattern available.

The more modern task-based pattern is much nicer for a number of reasons, including type-safety, simpler error handling, continuations, When*() methods, and others.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top