gpt4 book ai didi

.net - 在 Task.Run() 中包装同步调用以使其异步有益吗?

转载 作者:行者123 更新时间:2023-12-01 08:34:38 25 4
gpt4 key购买 nike

我提出这个问题的动机是因为我正在创建一个 .net web API 项目,该项目将使用具有同步方法的现有 neo4j rest api 客户端。我想通过使用异步方法来利用一些性能提升,但我想避免进入 neo4j api 库并重构同步方法以返回异步方法。我想知道在 await Task.Run() 中包装对同步方法的调用是否有好处。具体来说,在第一个示例中,当 httpClient 的异步结果调用 Wait() 方法时会发生什么,但整个过程都包含在另一个 await 中。

还请记住,我将在 AppHarbor 云上使用我认为的单个虚拟核心运行它。

下面也是

  //what happens with the synchronous rest api client I am using
HttpResponseMessage SendHttpRequest(HttpRequestMessage request)
{

var requestTask = httpClient.SendAsync(request);
requestTask.Wait();
return requestTask.Result;

}

object result = await Task.Run(() =>
{
return SendHttpRequest(request);
});

性能类似于
 return httpClient.SendAsync(request)

最佳答案

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.



对不起,您失去了 async的所有好处如果您只是将同步代码包装在 Task.Run 中,则在服务器端.
async在服务器上很好,因为异步操作比线程更好地扩展。但如果你使用 Task.Run ,那么您无论如何都在使用线程。

关于.net - 在 Task.Run() 中包装同步调用以使其异步有益吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13071833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com