是什么betweek等待任务&LT的差异; T>和任务< T>。结果? [英] What is the difference betweek await Task<T> and Task<T>.Result?

查看:191
本文介绍了是什么betweek等待任务&LT的差异; T>和任务< T>。结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公共异步任务<串GT;的GetName(INT ID)
    {
        任务<串GT; nameTask =
            Task.Factory.StartNew(()=> {返回的String.Format(名称匹配id {0} =开发,身份证);});
        返回nameTask.Result;
    }

在上面的方法return语句我使用Task.Result属性。

 公共异步任务<串GT;的GetName(INT ID)
    {
        任务<串GT; nameTask =
            Task.Factory.StartNew(()=> {返回的String.Format(名称匹配id {0} =开发,身份证);});
        返回等待nameTask;
    }

我在这里使用的await任务。我不会是错的,如果我认为等待将释放调用线程,但Task.Result会阻止它,这将是正确的?


解决方案

  

我不会是错的,如果我认为等待将释放调用线程,但Task.Result会阻止它,这将是正确的?


一般情况下,是的。 等待任务; 将收益当前线程。 task.Result 将阻止当前线程。 等待是一个异步等待; 结果是一个阻塞等待。

还有另一个更小的差异:如果任务在故障状态结束(即,异常),那么等待将(重新)提高了AS-例外是的,但结果将包装在异常的 AggregateException

作为一个方面说明,避免 Task.Factory.StartNew 。这是几乎从来没有使用正确的方法。如果您需要在后台线程执行工作,preFER Task.Run

// MSDN:

两者结果 StartNew 如果你正在做的dynamic任务并行;否则,它们应该被避免。如果你正在做异步编程也不是合适的。

 public async Task<string> GetName(int id)
    {
        Task<string> nameTask =
            Task.Factory.StartNew(() => { return string.Format("Name matching id {0} = Developer", id); });
        return nameTask.Result;
    }

In above method return statement I am using Task.Result property.

public async Task<string> GetName(int id)
    {
        Task<string> nameTask =
            Task.Factory.StartNew(() => { return string.Format("Name matching id {0} = Developer", id); });
        return await nameTask;
    }

Here I am using await Task. I wont be wrong if I think that await will release the calling thread but Task.Result will block it, would it be right?

解决方案

I wont be wrong if I think that await will release the calling thread but Task.Result will block it, would it be right?

Generally, yes. await task; will "yield" the current thread. task.Result will block the current thread. await is an asynchronous wait; Result is a blocking wait.

There's another more minor difference: if the task completes in a faulted state (i.e., with an exception), then await will (re-)raise that exception as-is, but Result will wrap the exception in an AggregateException.

As a side note, avoid Task.Factory.StartNew. It's almost never the correct method to use. If you need to execute work on a background thread, prefer Task.Run.

Both Result and StartNew are appropriate if you are doing dynamic task parallelism; otherwise, they should be avoided. Neither is appropriate if you are doing asynchronous programming.

这篇关于是什么betweek等待任务&LT的差异; T&GT;和任务&LT; T&GT;。结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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