如何:使用 ASP.NET 2.0 实现事件驱动的异步 Web 服务客户端
在 .NET Framework 2.0 版中,Web 服务描述语言工具 (Wsdl.exe) 生成的代理代码支持新增的event-driven asynchronous programming model。 通过将事件驱动的异步编程模型与 ASP.NET 2.0 Web 客户端的自动代理生成相结合,您可以快速生成基于 Web 服务的高性能 Web 应用程序。
Multithreaded Programming with the Event-based Asynchronous Pattern介绍一种新增的异步编程模型,该模型使用事件来处理回调,使得生成多线程应用程序更加容易,并且无需实现复杂的多线程代码本身。 有关新增的事件驱动的异步模型的概述,请参见Event-based Asynchronous Pattern Overview。 有关使用该新增模型的客户端实现的详细信息,请参见How to: Implement a Client of the Event-based Asynchronous Pattern。
在 .NET Framework 2.0 版中使用 ASP.NET 应用程序生成的 Web 服务客户端可以利用新增的 App_WebReferences 子目录,这样便可在客户端 ASP.NET 应用程序调用支持 WSDL 协定的 XML Web services 时将 WSDL 文件动态编译为代理代码。
有关完整示例,请参见 ASP.NET Web Services QuickStarts中的 RADAsync 快速入门。
实现事件驱动的 Web 服务客户端
使用同步 Web 方法创建 XML Web services,该 Web 方法执行某些最好异步执行的耗时行为。
[WebMethod] public string HelloWorld() { Thread.Sleep(5000); return "Hello World"; }
<WebMethod()> _ Public Function HelloWorld() As String Thread.Sleep(5000) ..Return "Hello World" End Function
在客户端 ASP.NET 应用程序中,将 Async 属性添加到 @ Page 指令中,并将其设置为 true,然后使用 @ Import 指令导入
System.Threading
命名空间。<%@ Page Language="C#" Debug="true" Async="true" %> <%@ Import Namespace="System.Threading" %>
<%@ Page Language="VB" Debug="true" Async="true" %> <%@ Import Namespace="System.Threading" %>
若要使用自动代理生成,请生成一个 WSDL 文件(使用 Web 服务描述语言工具 (Wsdl.exe))并将该文件放入客户端的 App_WebReferences 子目录中。 (有关详细信息,请参见 ASP.NET Web Site Layout。)
通过使用服务类名称和字符串
WaitService
创建一个新对象来正常地生成 Web 服务客户端应用程序,然后将 Web 服务 URL 分配给 Url 属性。 例如,如果服务类名是HelloWorld
,则客户端会创建一个HelloWorldWaitService
对象。HelloWorldWaitService service = new HelloWorldWaitService(); service.Url = "https://localhost/QuickStartv20/webservices/Samples/RADAsync/cs/Server/HelloWorldWaitService.asmx";
Dim service As New HelloWorldWaitService() service.Url = "https://localhost/QuickStartv20/webservices/Samples/RADAsync/vb/Server/HelloWorldWaitService.asmx"
在客户端应用程序代码中,将事件处理程序分配给代理的 Completed 事件。 在下面的代码示例中,客户端 ASP.NET 页有一个
HelloWorldCompleted
方法,当 Web 服务方法返回时就调用该方法。//Add our callback function to the event handler. service.HelloWorldCompleted += this.HelloWorldCompleted;
'Add our callback function to the event handler AddHandler service.HelloWorldCompleted, AddressOf Me.HelloWorldCompleted
在客户端应用程序代码中,对代理调用 Async 方法。 (此方法与该 Web 方法同名,但追加了“Async”。 有关详细信息,请参见How to: Implement a Client of the Event-based Asynchronous Pattern。) 此方法调用在客户端 ASP.NET 页中显示为同步调用,但它会立即返回。 在该异步调用完成,代理的 Completed 事件引发以及处理程序方法已经执行之前,客户端 ASP.NET 页不会返回到浏览器。
service.HelloWorldAsync("second call");
service.HelloWorldAsync("second call")
请参见
其他资源
ASP.NET Web Services QuickStarts
版权所有 (C) 2007 Microsoft Corporation。保留所有权利。