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

前端 未结 2 1978
野的像风
野的像风 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.

    0 讨论(0)
  • 2021-01-14 06:19

    I'd like to take advantage of some of the performance gains by going to asynchronous methods, but I want to avoid going into the neo4j api library and refactoring the synchronous methods to return async methods.

    Sorry, you lose all the benefits of async on the server side if you just wrap synchronous code in Task.Run.

    async is good on servers because asynchronous operations scale better than threads. But if you're using Task.Run, then you're using a thread anyway.

    0 讨论(0)
提交回复
热议问题