简体   繁体   中英

Task<T> vs Asynchronous delegates in c#?

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 ?

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 :)

任务更优雅,并且最近被引入(.Net 4)所以如果它满足您的需求,我会继续使用它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM