如何:创建异步 Web 服务方法

来源:互联网 发布:阿里云推荐码在哪里查 编辑:程序博客网 时间:2024/05/05 19:12

本过程描述如何将 Web 服务方法转换为为异步访问设计的方法对。该过程遵循 .NET Framework 的异步设计模式。异步 XML Web 服务方法主题说明如何使用本过程以及 Wsdl.exe 工具如何生成可以异步访问 Web 服务方法的客户端代理类,即使这些类是针对同步访问而设计的。

实现异步 Web 服务方法

  1. 将一个异步 Web 服务方法拆分成两个方法;每个方法都有相同的基名称,一个以 Begin 开头,另一个以 End 开头。

  2. Begin 方法的参数列表包含方法功能的所有 in 和 by reference 参数以及两个附加参数。

    • by reference 参数作为 in 参数列出。

    • 倒数第二个参数必须为 AsyncCallback。AsyncCallback 参数允许客户端提供委托,在方法完成时将调用该委托。当一个异步 Web 服务方法调用另一个异步方法时,此参数可被传递到该方法的倒数第二个参数。

    • 最后一个参数是 Object。Object 参数允许调用方为方法提供状态信息。当一个异步 Web 服务方法调用另一个异步方法时,此参数可以传递给该方法的最后一个参数。

    • 返回值必须为 IAsyncResult 类型。

  3. End 方法的参数列表包含 IAsyncResult 参数,此参数后面带有特定于方法功能的任何 out 和 by reference 参数。

    • 返回值类型与异步 Web 服务方法的返回值类型相同。

    • by reference 参数作为 out 参数列出。

示例

C#
复制代码
using System;using System.Web.Services;[WebService(Namespace="http://www.contoso.com/")]public class MyService : WebService {    public RemoteService remoteService;    public MyService()     {        // Create a new instance of proxy class for         // the Web service to be called.        remoteService = new RemoteService();    }    // Define the Begin method.    [WebMethod]    public IAsyncResult BeginGetAuthorRoyalties(String Author,        AsyncCallback callback, object asyncState)     {        // Begin asynchronous communictation with a different XML Web        // service.        return remoteService.BeginReturnedStronglyTypedDS(Author,            callback,asyncState);    }    // Define the End method.    [WebMethod]    public AuthorRoyalties EndGetAuthorRoyalties(IAsyncResult        asyncResult)     {        // Return the asynchronous result from the other Web service.        return remoteService.EndReturnedStronglyTypedDS(asyncResult);    }}
Visual Basic
复制代码
Imports System.Web.Services<WebService(Namespace:="http://www.contoso.com/")> _Public Class MyService    Inherits WebService    Public remoteService As RemoteService    Public Sub New()        MyBase.New()        ' Create a new instance of proxy class for         ' the Web service to be called.        remoteService = New RemoteService()    End Sub    ' Define the Begin method.    <WebMethod()> _    Public Function BeginGetAuthorRoyalties(ByVal Author As String, _    ByVal callback As AsyncCallback, ByVal asyncState As Object) _        As IAsyncResult        ' Begin asynchronous communictation with a different XML Web        ' service.        Return remoteService.BeginReturnedStronglyTypedDS(Author, _            callback, asyncState)    End Function    ' Define the End method.    <WebMethod()> _    Public Function EndGetAuthorRoyalties(ByVal asyncResult As _        IAsyncResult) As AuthorRoyalties        ' Return the asynchronous result from the other Web service.        Return remoteService.EndReturnedStronglyTypedDS(asyncResult)    End FunctionEnd Class

请参见

 
原创粉丝点击