本文介绍了是什么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会阻止它,这将是正确的?


解决方案

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>和任务< T>。结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:28