3.3 通过WPF应用程序调用Web API(C#)(转)

【ASP.NET Web API教程】3.3 通过WPF应用程序调用Web API(C#)

 

注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。

3.3 Calling a Web API From a WPF Application (C#)
3.3 通过WPF应用程序调用Web API(C#)

本文引自:http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-wpf-application

By Mike Wasson | August 22, 2012
作者:Mike Wasson | 日期:2012-8-22

This tutorial shows how to call a web API from a Windows Presentation Foundation (WPF) application, using HttpClient.
本教程展示如何用HttpClient通过WPF应用程序(Windows Presentation Foundation — Windows表现基础,WPF应用程序指常规的窗口应用程序 — 译者注)调用Web API。

The main purpose of this tutorial is to see how asynchronous operations are handled in HttpClient. In this tutorial, we will consume the "ProductStore" API, described in "Creating a Web API that Supports CRUD Operations". 
本教程的主要目的是考查在HttpClient中如何处理异步操作。在本教程中,我们将使用在“创建支持CRUD操作的Web API”小节中描述的“ProductStore”API。

Before you read this tutorial, you might want to read Calling a Web API From a .NET Client. That article introduces some of the concepts that I use in this tutorial.
在阅读这篇文章之前,你或许想阅读“通过.NET客户端调用Web API”(本系列教程的上一小节 — 译者注)。这篇文章中介绍了本教程使用的一些概念。

Asynchronous Calls
异步调用

HttpClient is designed to be non-blocking. Potentially long-running operations are implemented as asynchonrous methods, such as GetAsync and PostAsync. These methods return without waiting for the operation to complete. The previous tutorial (Calling a Web API From a Console Application) showed only blocking calls:
HttpClient被设计成是非阻塞的。潜在地,长时间运行的操作是作为异步方法实现的,例如,GetAsyncPostAsync。这些方法不会等待操作完成便会返回。上一教程(通过控制台应用程序调用Web API)只展示了阻塞调用:

HttpResponseMessage response = client.GetAsync("api/products").Result;  // Blocking call(阻塞)!

This code blocks the calling thread by taking the Result property. That's OK for a console application, but you should not do it from a UI thread, because it blocks the UI from responding to user input.
这段代码通过采用Result属性,会阻塞调用线程。对于一个控制台应用程序,这没问题,但你不应该在一个UI线程中采用这一做法,因为这会阻止UI去响应用户输入。

The asynchronous methods of HttpClient return Task objects that represent the asynchronous operation.
HttpClient的异步方法会返回表示异步操作的Task对象。

Create the WPF Project
创建WPF项目

Start Visual Studio. From the Start menu, select New Project. In the Templates pane, select Ins

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值