await Task< T>和之间的区别是什么?和Task< T>结果? [英] What is the difference between await Task<T> and Task<T>.Result?

查看:92
本文介绍了await Task< T>和之间的区别是什么?和Task< T>结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在上述方法返回语句中,我正在使用Task.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;
    }

我在这里使用等待任务.如果我认为await会释放调用线程,但Task.Result会阻止它,那我不会错,对吗?

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?

推荐答案

如果我认为await会释放调用线程,但Task.Result会阻止它,那我不会错,对吗?

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

通常,是的. await task;将屈服"当前线程. task.Result将阻止当前线程. await是异步等待; Result是阻塞等待.

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.

还有另一个较小的区别:如果任务在故障状态下完成(即有异常),则await将按原样(重新)引发该异常,但是Result会将异常包装在一个AggregateException.

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.

作为旁注,请避免使用Task.Factory.StartNew.几乎从来没有使用过正确的方法.如果需要在后台线程上执行工作,请选择Task.Run.

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.

如果您正在动态任务并行性,则ResultStartNew都是合适的 ;否则,应避免使用它们.如果您正在执行异步编程,则两者都不适用.

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.

这篇关于await Task&lt; T&gt;和之间的区别是什么?和Task&lt; T&gt;结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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