如何:使用等待技术实现异步 Web 服务客户端
等待技术是一种可实现与 Web 服务方法进行异步通信的 Web 服务客户端的方法,但该方法也可用于同步访问。 将在主题“与 XML Web services 进行异步通信”中解释该技术。
此示例基于具有 Factorize 方法的 Web 服务类 PrimeFactorizer,Wsdl.exe 工具已经为该类生成了两个异步客户端代理方法:BeginFactorize 和 EndFactorize。
实现等待技术
Web 服务客户端调用生成的代理类的 Begin 方法。
IAsyncResult ar = pf.BeginFactorize(factorizableNum, null, null);
Dim ar As IAsyncResult = pf.BeginFactorize(factorizableNum, _ Nothing, Nothing)
Web 服务客户端通过返回的 IAsyncResult 的 AsyncWaitHandle 属性访问 WaitHandle 对象。 该客户端将调用 WaitHandle 类的等待方法之一,然后等待一个或多个同步对象终止。
如果客户端只是使用此技术异步调用一个 Web 服务方法,它可以调用 WaitOne,以等待该方法完成处理。 其他等待方法为 WaitAny 和 WaitAll。
ar.AsyncWaitHandle.WaitOne();
ar.AsyncWaitHandle.WaitOne()
当等待方法返回时,客户端将调用 End 方法获取结果。
results = pf.EndFactorize(ar);
results = pf.EndFactorize(ar)
示例
// -----------------------------------------------------------------------// Async Variation 2.
// Asynchronously invoke the Factorize method,
//without specifying a call back.
using System;
using System.Runtime.Remoting.Messaging;
// MyFactorize, is the name of the namespace in which the proxy class is
// a member of for this sample.
using MyFactorize;
class TestCallback
{
public static void Main(){
long factorizableNum = 12345;
PrimeFactorizer pf = new PrimeFactorizer();
// Begin the Async call to Factorize.
IAsyncResult ar = pf.BeginFactorize(factorizableNum, null, null);
// Wait for the asynchronous operation to complete.
ar.AsyncWaitHandle.WaitOne();
// Get the completed results.
long[] results;
results = pf.EndFactorize(ar);
//Output the results.
Console.Write("12345 factors into: ");
int j;
for (j = 0; j<results.Length;j++){
if (j == results.Length - 1)
Console.WriteLine(results[j]);
else
Console.Write(results[j] + ", ");
}
}
}
Imports System
Imports System.Runtime.Remoting.Messaging
Imports MyFactorize ' Proxy class namespace
Public Class TestCallback
Public Shared Sub Main()
Dim factorizableNum As Long = 12345
Dim pf As PrimeFactorizer = new PrimeFactorizer()
' Begin the Async call to Factorize.
Dim ar As IAsyncResult = pf.BeginFactorize(factorizableNum, Nothing, Nothing)
' Wait for the asynchronous operation to complete.
ar.AsyncWaitHandle.WaitOne()
' Get the completed results.
Dim results() as Long
results = pf.EndFactorize(ar)
'Output the results.
Console.Write("12345 factors into: ")
Dim j as Integer
For j = 0 To results.Length - 1
If j = (results.Length - 1) Then
Console.WriteLine(results(j) )
Else
Console.Write(results(j).ToString + ", ")
End If
Next j
End Sub
End Class
请参见
任务
如何:使用回调技术实现异步 Web 服务客户端
如何:从 Web 服务客户端进行异步调用
概念
与 XML Web services 进行异步通信
生成 XML Web services 客户端
其他资源
版权所有 (C) 2007 Microsoft Corporation。保留所有权利。