【发布时间】:2015-09-14 14:08:50
【问题描述】:
我有一个调用外部 Web 服务的 Web 服务。外部服务会在 3-4 秒后响应。
现在所有的调用都是同步的,但是使用异步调用是否有意义(下面的示例)?
它是否有助于提高性能(不保持线程阻塞)? GetData() 第一行线程不是阻塞了吗?
谢谢。
public class MyService : WebService
{
[WebMethod]
public string GetData()
{
string response = ExecuteRequest(externalUrl, someContent).Result;
return response;
}
private async Task<string> ExecuteRequest(string url, string content)
{
var httpResponse = await new HttpClient().PostAsync(url, new StringContent(content));
string responseStr = await httpResponse.Content.ReadAsStringAsync();
return responseStr;
}
}
【问题讨论】:
-
为什么不让
GetData异步? -
那不需要修改调用我服务的客户端吗?
-
我不确定死锁线程 (stackoverflow.com/questions/13140523/…) 对性能有何帮助 :)... 如果您知道自己在做什么,那么很难让从同步代码调用的异步方法正常工作并且如果你不这样做,那真是个坏主意。
-
不,客户端没有区别 - 远程调用本质上始终是异步的,因此客户端不会看到任何行为变化。
-
在不知道应用程序的负载配置文件的情况下,没有人可以知道。我将把我关于如何决定是同步还是异步的标准处理方法联系起来:stackoverflow.com/a/25087273/122718 为什么 EF 6 教程使用异步调用? stackoverflow.com/a/12796711/122718我们应该切换到默认使用异步 I/O 吗?
标签: c# web-services asynchronous