Difference between passing a regular and async anonymous function to Task.Run for asynchronous work

筅森魡賤 提交于 2020-01-30 10:50:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!