在學習Web API的基礎課程 Calling a Web API From a .NET Client (C#) 中,作者介紹了如何客戶端調用WEB API,並給了示例代碼。
但是,那些代碼並不是非阻塞調用,作者還說下一章節會介紹異步調用這些方法的正確方法(I'll show the correct way to invoke those methods asynchronously).
可是我再也沒找到下文……
這里有篇參考譯文:http://www.cnblogs.com/r01cn/archive/2012/11/20/2779011.html
但是樓主也沒有回答樓下小伙伴的問題——異步非阻塞調用webapi(后來我給回答了,(*^__^*) 嘻嘻……)
基於以上原因,我在這里做個demo
其實就是將原文中的代碼:(參考代碼,僅作說明)
class Program { static void Main() { RunAsync().Wait(); } static async Task RunAsync() { using (var client = new HttpClient()) { // TODO - Send HTTP requests } } }
改為如下:
class Program { static void Main() { RunAsync(); } static async RunAsync() { using (var client = new HttpClient()) { // TODO - Send HTTP requests } } }
即不返回Tast了。
那阻塞跟非阻塞的區別在哪呢?
HttpResponseMessage response = await client.GetAsync("api/products/2");//非阻塞 //HttpResponseMessage response = client.GetAsync("api/products/2").Result; //阻塞
通過上面的代碼可以看出:采用Result屬性的過程是線程阻塞的。