通过.NET客户端异步调用Web API(C#)

 

在学习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属性的过程是线程阻塞的。

 

示例代码

 

posted @ 2014-04-19 16:42  zzhi.wang  阅读(4103)  评论(0编辑  收藏  举报