简体   繁体   English

任务 <T> vs c#中的异步委托?

[英]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. 第二种形式,使用IAsyncResult ,显着更老,功能更强大。 Task<T> was introduced in .NET 4, and is the preferred way of representing asynchronous operations now. Task<T>是在.NET 4中引入的,是现在表示异步操作的首选方式。 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. 它使用起来要简单得多,特别是在支持“异步函数”的C#5中,您可以以非阻塞方式等待任务(或其他异步操作)。

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. 使用Task而不是调用BeginInvoke可能不会改变操作本身的执行方式(尽管它在调度等方面为您提供了更多选项),但是从想要“代码”的角度来看,它有很大的不同。观察“操作,使用结果,等待多个任务,处理故障等

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. 如果您可以使用C#5(使用.NET 4.5,或使用.NET 4加上异步目标包),那么在管理异步操作时,它将使您的生活变得更加轻松。 It's the way forward :) 这是前进的方式:)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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