HOW TO:使用 ASP.NET 2.0 實作事件驅動的非同步 Web 服務用戶端

在 .NET Framework 2.0 版中,Web 服務描述語言工具 (Wsdl.exe) 產生的 Proxy 程式碼會支援新的event-driven asynchronous programming model。將事件驅動的非同步程式設計模型與 ASP.NET 2.0 Web 用戶端自動產生 Proxy 的作業結合起來,您就可以迅速建置以 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 Service 時,這個子目錄能夠動態地將 WSDL 檔案編譯成 Proxy 程式碼。

如需完整範例,請參閱 ASP.NET Web Services QuickStarts中的 RADAsync 快速入門。

實作事件驅動的 Web 服務用戶端

  1. 建立具有同步 Web 方法的 XML Web Service,這個方法會執行某個較耗時而最好以非同步方式完成的行為。

    [WebMethod]
    public string HelloWorld() {
      Thread.Sleep(5000);
      return "Hello World";
    }
    
    <WebMethod()> _
    Public Function HelloWorld() As String 
      Thread.Sleep(5000)
    ..Return "Hello World"
    End Function
    
  2. 在用戶端 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" %>
    
  3. 若要使用自動 Proxy 產生作業,請製作 WSDL 檔案 (使用 Web 服務描述語言工具 (Wsdl.exe)),然後將檔案放在用戶端的 App_WebReferences 子目錄中 (如需詳細資訊,請參閱 ASP.NET Web Site Layout)。

  4. 使用服務類別名稱加上字串 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"
    
  5. 在用戶端應用程式的程式碼中,將事件處理常式指派給 Proxy 的 Completed 事件。在下列程式碼範例中,用戶端 ASP.NET 網頁有一個要在 Web 服務方法回傳時呼叫的 HelloWorldCompleted 方法。

    //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
    
  6. 在用戶端應用程式的程式碼中,呼叫 Proxy 上的 Async 方法 (這個方法的名稱與 Web 方法相同,但是附加了 "Async"。如需詳細資訊,請參閱 How to: Implement a Client of the Event-based Asynchronous Pattern)。這個方法呼叫在用戶端 ASP.NET 網頁中顯示為同步呼叫,但是會立即回傳。而一般則是要等到非同步呼叫完成、引發 Proxy 的 Completed 事件並執行處理常式方法之後,才會將用戶端 ASP.NET 網頁傳回至瀏覽器。

    service.HelloWorldAsync("second call");
    
    service.HelloWorldAsync("second call")
    

請參閱

其他資源

ASP.NET Web Services QuickStarts

Footer image

Copyright © 2007 by Microsoft Corporation. All rights reserved.