是任务==懒惰? [英] Is Task == Lazy?

查看:126
本文介绍了是任务==懒惰?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public Data GetCurrent(Credentials credentials)
{ 
    var data = new Lazy<Data>(() => GetCurrentInternal(credentials));
    try
    {
        return data.Value;
    }
    catch (InvalidOperationException ex)
    {
        throw ex.InnerException;
    }
}

如果我改变调用如下:

var data = new Task<Data>(() => GetCurrentInternal(credentials));

有什么变化吗?我宁愿工作?关于什么的Dispose()赶上(例外)

Is there anything change? Should I prefer Task over Lazy? What about Dispose() and catch(Exception) ?

推荐答案

两者懒< T> 任务< T> 答应以后做一些工作,返回类型 T 的结果

Similarities

Both Lazy<T> and Task<T> promise to do some work later and return a result of type T.

懒< T> 承诺去做的工作,尽可能晚地,如果。需要在所有,这样做同步

Lazy<T> promises to do it's work as late as possible if it is required at all, and does so synchronously.

任务< T> 但能做到这一点的异步工作,而你。线程做其他工作,或等待结果块

Task<T> however can do it's work asynchronously while your thread does other work, or blocks awaiting result.

懒< T> 将泡涨所造成的任何异常拉姆达当你调用 .value的

Lazy<T> will bubble up any exception caused by the lambda when you call .Value.

任务< T> 将继续造成拉姆达任何异常,并把它后,当你等待任务。或者,如果你 task.Wait()它的可能的包裹在了exeception AggregationException 。我是指你这个更多的信息上醒目由任务引发的异常:抓通过异步方法抛出一个异常,这 HTTP ://stiller.co.il/blog/2012/12/task-wait-vs-await/

Task<T> will keep any exception caused by the lambda and throw it later when you await task. Or if you task.Wait() it may wrap the exeception in an AggregationException. I refer you to this for more info on catching exceptions thrown by tasks: Catch an exception thrown by an async method and this http://stiller.co.il/blog/2012/12/task-wait-vs-await/

这篇关于是任务==懒惰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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