await Task 和有什么区别?和任务<T>.结果?

await Task<T> 和有什么区别?和任务<T>.结果?

问题描述:

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

在上面的方法返回语句中,我使用了 Task.Result 属性.

In above method return statement I am using the Task<T>.Result property.

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

这里我使用的是await Task.如果我认为 await 会释放调用线程,但 Task.Result 会阻塞它,我不会错,对吗?

Here I am using await Task<T>. I wont be wrong if I think that await will release the calling thread but Task<T>.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 将(重新)按原样引发该异常,但 结果 会将异常包装在 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.