问题描述
我的动机这个问题,是因为我创建将利用现有的Neo4j的REST API客户端,具有同步方法的.NET Web API项目。我想利用一些性能提升通过将异步方法,但我想,以避免进入了Neo4j的API库和重构的同步方法返回异步方法。我在想,如果包裹调用在计谋Task.Run()的同步方法将是有益的。具体而言,是什么在第一个例子发生在从HttpClient的异步结果调用wait()方法,但整个事情是包裹在另一个等待。
另外请记住,我会在AppHarbor云中运行这个跟我相信这是一个虚拟的核心。
那么,以下
//与我使用的同步REST API客户端会发生什么
HTT presponseMessage SendHtt prequest(HTT prequestMessage要求)
{
VAR requestTask = httpClient.SendAsync(要求);
requestTask.Wait();
返回requestTask.Result;
}
对象result =等待Task.Run(()=>
{
返回SendHtt prequest(要求);
});
在性能上类似
返回httpClient.SendAsync(要求)
对不起,你失去了异步
在服务器端的所有好处,如果你只是包装在同步code Task.Run
。
异步
是好的服务器,因为异步操作规模比线程更好。但是,如果你使用 Task.Run
,然后你使用一个线程反正。
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 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. I was wondering if wrapping the calls to the synchronous methods in an await Task.Run() would be beneficial at all. Specifically, what happens in the first example when the async result from httpClient calls the Wait() method, but the whole thing is wrapped in another await.
Also keep in mind that I would be running this on AppHarbor cloud with what I believe is a single virtual core.
So is the following
//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);
});
similar in performance to
return httpClient.SendAsync(request)
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.
这篇关于被包裹在一个Task.Run同步调用(),使之异步有益?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!