2016-09-15 30 views
0

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

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

+0

Tl; Dr取决于 – Liam

回答

0

一般来说,异步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服务器将停止提供请求。至于你的特定问题 - 尝试一下,你会发现。

+0

我开始怀疑。我希望WebClient可能足够聪明,可以做异步,但可以将它隐藏起来:停止我的工作,释放线程,在请求返回时唤醒事情。我现在看到我太希望了! – bbsimonbb