Is Task == Lazy?

前端 未结 3 1194
予麋鹿
予麋鹿 2021-01-21 05:46
public Data GetCurrent(Credentials credentials)
{ 
    var data = new Lazy(() => GetCurrentInternal(credentials));
    try
    {
        return data.Value         


        
3条回答
  •  我在风中等你
    2021-01-21 05:59

    Similarities

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

    Differences

    Lazy promises to do its work as late as possible if it is required at all, and does so synchronously.

    Task however can do its work asynchronously while your thread does other work, or blocks awaiting result.

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

    Task 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 exception 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/

提交回复
热议问题