问题
What is the difference between
ResultType result = await Task.Run(() => GetResultAsync())
and
ResultType result = await Task.Run(async() => await GetResultAsync())
I would speculate that the former would fire and forget GetResultAsync()
, since it is not awaited, but then how does it get the result? I am surprised that the return type of the formerTask.Run
is Task<ResultType>
and not Task<Task<ResultType>>
.
回答1:
Both do the same from perspective of result. In both cases the overload Task.Run<TResult>(Func<Task<TResult>> function)
is used which internally unwraps the task - that's why result is Task<ResultType>
. The difference between them is equiavalent to the difference between
static Task<T> Compute()
{
return GetAsyncResult();
}
and
static async Task<T> Compute()
{
return await GetAsyncResult();
}
In the first case the promise is just passed back to the caller, while in the second the state machine is built by compiler around the Compute
method.
回答2:
In the first line the 'Task.Run' you start, immediately returns the result of 'GetResultAsync'. That result however, is a Task that can be awaited (by your 'await'). So, you actually 'await' the 'GetResultAsync' method.
In the second line, you start a Task that does not return immediately, but waits till 'GetResultAsync' (called asynchronously) is finished. The returntype of your Task is 'ResultType'. So you 'await' your own Task, that in its turn will only return after awaiting the 'GetResultAsync' method.
In the end, they both accomplish the same result, but in a slightly different manner.
来源:https://stackoverflow.com/questions/55187476/difference-between-passing-a-regular-and-async-anonymous-function-to-task-run-fo