是什么betweek等待任务&LT的差异; T&GT;和任务&LT; T&GT;。结果? [英] What is the difference betweek await Task<T> and Task<T>.Result?
问题描述
公共异步任务&LT;串GT;的GetName(INT ID)
{
任务&LT;串GT; nameTask =
Task.Factory.StartNew(()=&GT; {返回的String.Format(名称匹配id {0} =开发,身份证);});
返回nameTask.Result;
}
在上面的方法return语句我使用Task.Result属性。
公共异步任务&LT;串GT;的GetName(INT ID)
{
任务&LT;串GT; nameTask =
Task.Factory.StartNew(()=&GT; {返回的String.Format(名称匹配id {0} =开发,身份证);});
返回等待nameTask;
}
我在这里使用的await任务。我不会是错的,如果我认为等待将释放调用线程,但Task.Result会阻止它,这将是正确的?
我不会是错的,如果我认为等待将释放调用线程,但Task.Result会阻止它,这将是正确的?
块引用>一般情况下,是的。
等待任务;
将收益当前线程。task.Result
将阻止当前线程。等待
是一个异步等待;结果
是一个阻塞等待。还有另一个更小的差异:如果任务在故障状态结束(即,异常),那么
等待
将(重新)提高了AS-例外是的,但结果
将包装在异常的AggregateException
。作为一个方面说明,避免
// MSDN:Task.Factory.StartNew
。这是几乎从来没有使用正确的方法。如果您需要在后台线程执行工作,preFERTask.Run
。两者
结果
和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, butResult
will wrap the exception in anAggregateException
.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, preferTask.Run
.Both
Result
andStartNew
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屋!