ASP.NET建立Web服務之非同步Web服務1

來源:互聯網
上載者:User
ASP.NET建立Web服務之非同步Web服務1
 
  為了改善調用阻礙線程的長期啟動並執行方法的XML Web服務方法的效能,你應該考慮把它們作為非同步XML Web服務方法發布。實現一個非同步XML Web服務方法允許線程在返回線程池的時候執行其他的代碼。這允許增加一個線程池中的有限數目的線程,這樣提高了整體效能和系統的延展性。

  通常,調用執行輸入/輸出操作的方法的XML Web服務方法適於作為非同步實現。這樣的方法的例子包括和其他的XML Web服務通訊、訪問遠端資料庫、執行網路輸入/輸出和讀寫大檔案方法。這些方法都花費大量時間執行硬體級操作,而把線程留著用來執行XML Web服務方法程式塊。如果XML Web服務方法非同步實現,那麼線程可以被釋放來執行其他的代碼。

  不管一個XML Web服務方法是否非同步實現,用戶端都可以與之非同步通訊。使用Web服務描述語言工具(WSDL.EXE)產生的.NET用戶端中的代理類來實現非同步通訊,即使XML Web服務方法是同步實現。代理類包含用於與每個XML Web服務方法非同步通訊的Begin和End方法。因此,決定一個XML Web服務方法到底是非同步還是同步要取決於效能。

  注意:實現一個非同步XML Web服務方法對用戶端和伺服器上的XML Web服務之間的HTTP串連沒有影響。HTTP串連既不不會關閉也不用串連池化。

  實現一個非同步XML Web服務方法

  實現一個非同步XML Web服務方法遵循NET Framework非同步設計模式

  把一個同步的XML Web服務方法分解為兩個方法;其中每個都帶有相同的基名--一個帶有以Begin開頭的名稱,另一個帶有以End開頭的名稱。

  Begin方法的參數表包含方法的功能中的所有的in和by引用參數。

  By引用參數是作為輸入參數列出的。

  倒數第二個參數必須是AsyncCallback。AsyncCallback參數允許用戶端提供一個委託,在方法調用完成的時候調用。當一個非同步XML Web服務方法調用另一個非同步方法呼叫,這個參數可以被傳入那個方法的倒數第二個參數。最後一個參數是一個對象。對象參數允許一個調用者提供狀態資訊給方法。當一個非同步XML Web服務方法調用另一個非同步方法呼叫,這個參數可以被傳入那個方法的最後一個參數。

  傳回值必須是IAsyncResult類型的。

  下面的程式碼範例是一個Begin方法,有一個方法函數特定的String參數。

[C#]
[WebMethod]
public IAsyncResult BeginGetAuthorRoyalties(String Author,
AsyncCallback callback, object asyncState)
[Visual Basic]
<WebMethod()> _
Public Function BeginGetAuthorRoyalties(ByVal Author As String, _
ByVal callback As AsyncCallback, ByVal asyncState As Object) _
As IAsyncResult

  End方法的參數表由一個IAsyncResult類型的out和by引用參數組成。

  傳回值與一個同步的XML Web服務方法的傳回值類型相同。

  By引用參數是作為輸出參數列出的。

  下面的程式碼範例是一個End方法,返回一個AuthorRoyalties使用者定義的模式。

[C#]
[WebMethod]
public AuthorRoyalties EndGetAuthorRoyalties(IAsyncResult
asyncResult)

[Visual Basic]
<WebMethod()> _
Public Function EndGetAuthorRoyalties(ByVal asyncResult As _
IAsyncResult) As AuthorRoyalties

  下面的程式碼範例是一個和另一個XML Web服務方法非同步通訊的非同步XML Web服務方法。

[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 XML 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(IAsyncResultasyncResult) {
  // Return the asynchronous result from the other XML 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 XML 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 XML Web service.
 Return remoteService.EndReturnedStronglyTypedDS(asyncResult)
End Function
End Class

  下面的程式碼範例顯示當一個XML Web服務方法產生了一個以上的非同步呼叫並且這些調用必須連續執行時如何串連這些非同步呼叫。BeginGetAuthorRoyalties方法產生一個非同步呼叫用來判斷傳入的作者名是否有效,並設定一個名為AuthorRoyaltiesCallback的中間回調來接收結果。如果作者名有效,那麼那個中間回調非同步呼叫來獲得作者的版稅。

[C#]
using System.Web.Services;
using System.Data;
using System;
// This imports the proxy class for the XML Web services
// that the sample communicates with.
using AsyncWS.localhost;

namespace AsyncWS
{
 [WebService(Namespace="http://www.contoso.com/")]
 public class MyService : System.Web.Services.WebService
 {
  public RemoteService remoteService;
  public MyService()
  {
   remo teService = new RemoteService();
  }

 [WebMethod]
 public IAsyncResult BeginGetAuthorRoyalties(String Author,
 AsyncCallback callback, Object asyncState)
 {
  // Saves the current state for the call that gets the author's
  // royalties.
  AsyncStateChain state = new AsyncStateChain();
  state.originalState = asyncState;
  state.Author = Author;
  state.originalCallback = callback;

  // Creates an intermediary callback.
  AsyncCallback chainedCallback = new
  AsyncCallback(AuthorRoyaltiesCallback);
  return remoteService.BeginGetAuthors(chainedCallback,state);
 }
 // Intermediate method to handle chaining the
 // asynchronous calls.
 public void AuthorRoyaltiesCallback(IAsyncResult ar)
 {
  AsyncStateChain state = (AsyncStateChain)ar.AsyncState;
  RemoteService rs = new RemoteService();

  // Gets the result from the call to GetAuthors.
  Authors allAuthors = rs.EndGetAuthors(ar);

  Boolean found = false;
  // Verifies that the requested author is valid.
  int i = 0;
  DataRow row;
  while (i < allAuthors.authors.Rows.Count && !found)
  {
   row = allAuthors.authors.Rows[i];
   if (row["au_lname"].ToString() == state.Author)
   {
    found = true;
   }
   i++;
  }
  if (found)
  {
   AsyncCallback cb = state.originalCallback;
   // Calls the second XML Web service, because the author is
   // valid.
   rs.BeginReturnedStronglyTypedDS(state.Author,cb,state);
  }
  else
  {
   // Cannot throw the exception in this function or the XML Web
   // service will hang. So, set the state argument to the
   // exception and let the End method of the chained XML Web
   // service check for it.
   ArgumentException ex = new ArgumentException(
    "Author does not exist.","Author");
   AsyncCallback cb = state.originalCallback;
   // Call the second XML Web service, setting the state to an
   // exception.
   rs.BeginReturnedStronglyTypedDS(state.Author,cb,ex);
  }
 }

 [WebMethod]
 public AuthorRoyalties EndGetAuthorRoyalties(IAsyncResult asyncResult)
 {
  // Check whehter the first XML Web service threw an exception.
  if (asyncResult.AsyncState is ArgumentException)
   throw (ArgumentException) asyncResult.AsyncState;
  else
   return remoteService.EndReturnedStronglyTypedDS(asyncResult);
 }
}
// Class to wrap the callback and state for the intermediate
// asynchronous operation.
public class AsyncStateChain
{
 public AsyncCallback originalCallback;
 public Object originalState;
 public String Author;
}
}

[Visual Basic]

Imports System.Web.Services
Imports System.Data
Imports System
' This imports the proxy class for the XML Web services
' that the sample communicates with.
Imports AsyncWS_VB.localhost

Namespace AsyncWs

<WebService(Namespace:="http://www.contoso.com/")> _
Public Class MyService
Inherits WebService
Public remoteService As remoteService
Public Sub New()
MyBase.New()
remoteService = New localhost.RemoteService()
End Sub
' Defines the Begin method.
<WebMethod()> _
Public Function BeginGetAuthorRoyalties(ByVal Author As String, _
ByVal callback As AsyncCallback, ByVal asyncState As Object) _
As IAsyncResult
' Saves the current state for the call that gets the author's
' royalties.
Dim state As AsyncStateChain = New AsyncStateChain()
state.originalState = asyncState
state.Author = Author
state.originalCallback = callback

' Creates an intermediary callback.
Dim chainedCallback As AsyncCallback = New AsyncCallback( _
AddressOf AuthorRoyaltiesCallback)
' Begin asynchronous communictation with a different XML Web
' service.
Return remoteService.BeginGetAuthors(chainedCallback, state)
End Function

' Intermediate method to handle chaining the asynchronous calls.
Public Sub AuthorRoyaltiesCallback(ByVal ar As IAsyncResult)
Dim state As AsyncStateChain = CType(ar.AsyncState, _
AsyncStateChain)
Dim rs As RemoteService = New RemoteService()

' Gets the result from the call to GetAuthors.
Dim allAuthors As Authors = rs.EndGetAuthors(ar)
Dim found As Boolean = False

' Verifies that the requested author is valid.
Dim i As Integer = 0
Dim row As DataRow
While (i < allAuthors.authors.Rows.Count And (Not found))
 row = allAuthors.authors.Rows(i)
 If (row("au_lname").ToString() = state.Author) Then
  found = True
 End If
 i = i + 1
End While

If (found) Then
 Dim cb As AsyncCallback = state.originalCallback
 ' Calls the second XML Web service, because the author is
 ' valid.
 rs.BeginReturnedStronglyTypedDS(state.Author, cb, state)
Else
 ' Cannot throw the exception in this function or the XML Web
 ' service will hang. So, set the state argument to the
 ' exception and let the End method of the chained XML Web
 ' service check for it.
 Dim ex As ArgumentException = New ArgumentException( "Author does not exist.", "Author")
 Dim cb As AsyncCallback = state.originalCallback
 ' Call the second XML Web service, setting the state to an
 ' exception.
 rs.BeginReturnedStronglyTypedDS(state.Author, cb, ex)
End If
End Sub

' Define the End method.
<WebMethod()> _
Public Function EndGetAuthorRoyalties(ByVal asyncResult As _
IAsyncResult) As localhost.AuthorRoyalties
 ' Return the asynchronous result from the other XML Web service.
 Return remoteService.EndReturnedStronglyTypedDS(asyncResult)
End Function

End Class

' Class to wrap the callback and state for the intermediate asynchronous
' operation.
Public Class AsyncStateChain
Public originalCallback As AsyncCallback
Public originalState As Object
Public Author As String
End Class
End Namespace

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.