System.Net.WebClient - 我应该使用Async

时间:2016-09-15 09:43:08

标签: c# web-services

我有一个C#Web应用程序,它进行Web服务调用,然后为浏览器呈现页面。在this advice之后,我选择使用System.Net.WebClient作为请求,因为它有一个succint接口和我需要的所有控件。

WebClient为我提供了所有下载方法的异步版本。我应该使用它们吗?如果当前用户等待,我不在乎。在我可以呈现页面之前,我需要Web服务结果,在此期间我没有别的事情要做(对她而言)。但是,如果我的服务器在一个用户的Web服务调用完成时被捆绑,我真的很在意。如果这是javascript,主线程上的同步Web请求将至少占用整个窗口。这是asp.net中的情况吗?由于我无法控制的原因,我的Web服务请求位于一堆15个方法调用的底部。 Dot我必须将它们全部转换为异步才能看到任何优势吗?

1 个答案:

答案 0 :(得分:0)

一般来说,async IO不会产生更快的每请求响应,但理论上它可以提高吞吐量。

public async Task<IActionResult> YourWebApiMethod() {
  // at this point thread serving this request is returned back to threadpool and   
  // awailable to serve other requests
  var result = await Call3ptyService();
  // once IO is finished we grab new thread from thread pool to finish the job
  return result;
}

// thread serving this request is allocated for duration of whole operation 
public IActionResult YourWebApiMethod() {
  return Call3ptyService().Result;
}

如果每个线程忙于等待外部服务,那么线程池中只有这么多线程;您的Web服务器将停止提供请求。至于你的特殊问题 - 尝试一下,你就会发现。