Is wrapping a synchronous call in a Task.Run() to make it asynchronous beneficial?

前端 未结 2 1993
野的像风
野的像风 2021-01-14 05:44

My motivation for this question is because I am creating a .net web API project that would be using an existing neo4j rest api client that has synchronous methods. I\'d lik

2条回答
  •  失恋的感觉
    2021-01-14 06:05

    The difference is that the Task.Run method simply runs the same blocking code on the threadpool. This means that while it won't block your calling thread, it will block the execution thread.

    How much this matters is entirely down to resources and performance considerations.

    If the SendHttpRequest method truly is simply waiting on the httpClient.SendAsync Task you could simply avoid that method and write:

    object result = await httpClient.SendAsync(request);
    

    Or:

    object result = await Task.Run(async () => await httpClient.SendAsync(request));
    

    If the SendAsync task still should be run on a separate thread.

提交回复
热议问题