任务< T> VS在C#中异步委托? [英] Task<T> vs Asynchronous delegates in c#?

查看:76
本文介绍了任务< T> VS在C#中异步委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的方法:

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

  • 他们都使用一个线程池线程。
  • 从等待执行完成(读值时)
  • 在这两种再次引发任何异常给调用者。
  • 我应该何时使用的呢?

    When Should I use each ?

    推荐答案

    第二种形式,使用的IAsyncResult ,是显著年纪大了,更不强大。 任务&LT; T&GT; 被引入.NET 4中,并重新presenting异步操作的preferred方式了。它更易于使用,特别是在C#5,其支持异步函数在这里可以等待一个任务(或其它异步操作)在非阻塞方法

    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.

    使用的工作不是调用的BeginInvoke 可能不会有太大变化如何操作本身执行(虽然它为您提供了调度等方面)更多的选择,但它使一个巨大的差异,从的code这要看的操作,使用的结果,等待多个任务,处理故障等角度

    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.

    如果你都不可能用C#5(无论是与.NET 4.5,或.NET 4中加上异步针对包),它会让你的生活相当容易,当它涉及到管理异步操作。这是前进的道路:)

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

    这篇关于任务&LT; T&GT; VS在C#中异步委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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