Task vs Asynchronous delegates in c#?

2019-04-05 04:33发布

问题:

I have this simple method :

static int Work (string s) { return s.Length; }

I could run it with :

Task<string> task = Task.Factory.StartNew<int> (() => Work ("lalala") );
...
int result = task.Result;

Or with this :

Func<string, int> method = Work;
IAsyncResult myIasync= method.BeginInvoke ("lalala", null, null);
...
int result = method.EndInvoke (myIasync);
  • They both use a threadpool thread.
  • Both wait the execution to finish ( when reading the value)
  • Both rethrow any exception to the caller.

When Should I use each ?

回答1:

The second form, using IAsyncResult, is significantly older, and much less powerful. Task<T> was introduced in .NET 4, and is the preferred way of representing asynchronous operations now. It's much simpler to use, particularly in C# 5 which supports "asynchronous functions" where you can await a task (or other asynchronous operation) in a non-blocking way.

Using a Task instead of calling BeginInvoke probably won't change much about how the operation itself is executed (although it gives you more options in terms of scheduling etc), but it makes a huge difference from the perspective of the code which wants to "watch" the operation, use the results, wait for multiple tasks, handle failures etc.

If you can possibly use C# 5 (either with .NET 4.5, or with .NET 4 plus the async targeting pack) it will make your life considerably easier when it comes to managing asynchronous operations. It's the way forward :)



回答2:

Task is more elegant, and was introduced more recently (.Net 4) so if it meets your needs, I'd go with that.