為了改善調用阻礙線程的長期運行的方法的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 
  和xml web服務異步地通訊
和一個xml web服務異步通訊遵循被microsoft.net framework其它部分使用的異步設計模式。然而,在你取得那些細節之前,重要的是注意一個xml web服務不必特意的寫來處理用于異步調用的異步請求。你使用wsdl.exe為你的客戶端創建的代理類自動地創建用于異步調用xml web服務方法的方法。即使只有一個xml web服務方法的同步實現也是這樣的。
.net framework異步方法調用設計模式
用于調用異步方法的設計模式,尤其是用于.net framework,針對每個同步方法分別有兩個異步方法。對每個同步方法,都有一個begin異步方法和一個end異步方法。begin方法被客戶端調用來開始方法調用。也就是說,客戶端指示這個方法來開始處理方法調用,但是立即返回。end方法被客戶端調用來取得xml web服務方法調用執行的處理結果。
一個客戶端如何知道何時調用end方法?.net framework定義了兩種方法來實現客戶端判斷其時間。第一種是傳送一個回調函數到begin方法,當方法已經完成處理的時候調用。第二個方法是使用waithandle類的一個方法來導致客戶端等待方法完成。當一個客戶端實現第二個方法,并且調用begin方法,返回值不是xml web服務方法指定的數據類型,而是一個實現iasyncresult接口的類型。iasyncresult接口包含一個waithandle類型的asyncwaithandle屬性,實現支持等待同步對象變為帶有waithandle.waitone、waitany和waitall標記的方法。當一個同步對象被標記的時候,它指示等待特定的資源的線程可以訪問資源的。如果一個xml web服務客戶端使用wait方法僅僅異步地調用一個xml web服務方法,那么它可以調用waitone來等待xml web服務方法完成處理。
重要的是注意不管客戶端選擇來與xml web服務異步通訊的兩種方法中的哪一種,soap消息發送和接收都與同步通信時吻合。也就是說,只有一個soap請求和soap響應通過網絡發送和接收。代理類通過使用一個不同的線程而不是客戶端用來調用begin方法的線程來處理soap響應。因此,客戶端可以繼續執行線程上的其它的工作,而代理類處理接收和操作soap響應。
實現一個產生異步的方法調用的xml web服務客戶端
用于從使用asp.net創建的xml web服務客戶端產生一個到xml web服務的異步調用的體系結構被嵌入.net framework和由wsdl.exe構造的代理類中。用于異步調用的設計模式被.net framework定義,代理類提供和一個xml web服務異步通信的機制。當一個用于xml web服務的代理類被使用wsdl.exe構造的時候,有三個方法分別被創建,用于xml web服務中的公共xml web服務方法。下面的表格描述那三個方法。
代理類中的方法名 描述
<nameofwebservicemethod> 同步發送用于名為<nameofwebservicemethod>的xml web服務方法的消息。
begin<nameofwebservicemethod> 開始與名為<nameofwebservicemethod>的xml web服務方法的異步消息通信。
end<nameofwebservicemethod> 結束與名為<nameofwebservicemethod>的xml web服務方法的異步消息通信,從xml web服務方法中取得完成的消息。
下面的代碼示例是一個xml web服務方法,它可能花費相對長的時間來完成處理。因此,當你應該設置你的xml web服務客戶端來異步地調用xml web服務方法的時候,它是一個很好的示例。
[c#]
<%@ webservice language="c#" class="primefactorizer" %>
using system;
using system.collections;
using system.web.services;
class primefactorizer {
 [webmethod]
 public long[] factorize(long factorizablenum){
  arraylist outlist = new arraylist();
  long i = 0;
  int j;
  try{
   long check = factorizablenum;
   //go through every possible integer
   //factor between 2 and factorizablenum / 2.
   //thus, for 21, check between 2 and 10.
   for (i = 2; i < (factorizablenum / 2); i++){
    while(check % i == 0){
     outlist.add(i);
     check = (check/i);
    }
   }
   //double-check to see how many prime factors have been added.
   //if none, add 1 and the number.
   j = outlist.count;
   if (j == 0) {
    outlist.add(1);
    outlist.add(factorizablenum);
   }
   j = outlist.count;
   //return the results and
   //create an array to hold them.
   long[] primefactor = new long[j];
   for (j = 0; j < outlist.count; j++){
    //pass the values one by one, making sure
    //to convert them to type ulong.
    primefactor[j] = convert.toint64(outlist[j]);
   }
   return primefactor;
  }
  catch (exception) {
   return null;
  }
 }
} 
[visual basic]
<%@ webservice class="primefactorizer" language="vb" %>
imports system
imports system.collections
imports system.web.services
public class primefactorizer 
<webmethod> _
public function factorize(factorizablenum as long) as long()
 dim outlist as new arraylist()
 dim i as long = 0
 dim j as integer
 try
  dim check as long = factorizablenum
  'go through every possible integer
  'factor between 2 and factorizablenum / 2.
  'thus, for 21, check between 2 and 10.
  for i = 2 to clng(factorizablenum / 2) - 1
   while check mod i = 0
    outlist.add(i)
    check = clng(check / i)
   end while
  next i
  'double-check to see how many prime factors have been added.
  'if none, add 1 and the number.
  j = outlist.count
  if j = 0 then
   outlist.add(1)
   outlist.add(factorizablenum)
  end if
  j = outlist.count
  'return the results and
  'create an array to hold them.
  dim primefactor(j - 1) as long
  for j = 0 to outlist.count - 1
   'pass the values one by one, making sure
   'to convert them to type ulong.
   primefactor(j) = clng(outlist(j))
  next j
  return primefactor
 catch
  return nothing
 end try
end function
end class 
下面的代碼示例是一個wsdl.exe生成的代理類的一部分,用于上述xml web服務方法。注意beginfactorize和endfactorize方法,因為它們被用來與factorize xml web服務方法異步通信。
public class primefactorizer : system.web.services.protocols.soaphttpclientprotocol {
 public long[] factorize(long factorizablenum) {
  object[] results = this.invoke("factorize", new object[] { factorizablenum});
   return ((long[])(results[0]));
 }
 public system.iasyncresult beginfactorize(long factorizablenum, system.asynccallback callback, object  asyncstate) {
  return this.begininvoke("factorize", new object[] {
  factorizablenum}, callback, asyncstate);
 }
 public long[] endfactorize(system.iasyncresult asyncresult) {
  object[] results = this.endinvoke(asyncresult);
  return ((long[])(results[0]));
 }
} 
有兩個方法用來和xml web服務方法異步通信。下面的代碼示例說明了如何與一個xml web服務方法異步通信,并且使用回調函數來取得xml web服務方法的結果。
[c#]
using system;
using system.runtime.remoting.messaging;
using myfactorize;
class testcallback
{ 
 public static void main(){
  long factorizablenum = 12345;
  primefactorizer pf = new primefactorizer();
  //instantiate an asynccallback delegate to use as a parameter
  //in the beginfactorize method.
  asynccallback cb = new asynccallback(testcallback.factorizecallback);
  // begin the async call to factorize, passing in our
  // asynccalback delegate and a reference
  // to our instance of primefactorizer.
  iasyncresult ar = pf.beginfactorize(factorizablenum, cb, pf);
  // keep track of the time it takes to complete the async call
  // as the call proceeds.
  int start = datetime.now.second;
  int currentsecond = start;
  while (ar.iscompleted == false){
   if (currentsecond < datetime.now.second) {
    currentsecond = datetime.now.second;
    console.writeline("seconds elapsed..." + (currentsecond - start).tostring() );
   }
  }
  // once the call has completed, you need a method to ensure the
  // thread executing this main function 
  // doesn't complete prior to the call-back function completing.
  console.write("press enter to quit");
  int quitchar = console.read();
 }
 // set up a call-back function that is invoked by the proxy class
 // when the asynchronous operation completes.
 public static void factorizecallback(iasyncresult ar)
 {
  // you passed in our instance of primefactorizer in the third
  // parameter to beginfactorize, which is accessible in the
  // asyncstate property.
  primefactorizer pf = (primefactorizer) ar.asyncstate;
  long[] results;
  // get the completed 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] + ", ");
  }
 }
}
[visual basic]
imports system
imports system.runtime.remoting.messaging
imports myfactorize
public class testcallback
public shared sub main()
dim factorizablenum as long = 12345
dim pf as primefactorizer = new primefactorizer()
'instantiate an asynccallback delegate to use as a parameter
' in the beginfactorize method.
dim cb as asynccallback 
cb = new asynccallback(addressof testcallback.factorizecallback)
' begin the async call to factorize, passing in the
' asynccallback delegate and a reference to our instance
' of primefactorizer.
dim ar as iasyncresult = pf.beginfactorize(factorizablenum, cb, pf)
' keep track of the time it takes to complete the async call as
' the call proceeds.
dim start as integer = datetime.now.second
dim currentsecond as integer = start
do while (ar.iscompleted = false)
if (currentsecond < datetime.now.second) then
 currentsecond = datetime.now.second
 console.writeline("seconds elapsed..." + (currentsecond - start).tostring() )
end if
loop
' once the call has completed, you need a method to ensure the
' thread executing this main function 
' doesn't complete prior to the callback function completing.
console.write("press enter to quit")
dim quitchar as integer = console.read()
end sub
' set up the call-back function that is invoked by the proxy 
' class when the asynchronous operation completes.
public shared sub factorizecallback(ar as iasyncresult)
' you passed in the instance of primefactorizer in the third
' parameter to beginfactorize, which is accessible in the
' asyncstate property.
dim pf as primefactorizer = ar.asyncstate
dim results() as long
' get the completed results.
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 
下面的代碼示例說明了如何與一個xml web服務方法異步通信,然后使用一個同步對象來等待處理結束。
[c#]
// -----------------------------------------------------------------------// 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] + ", ");
  }
 }
}
[visual basic]
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 
  注意:如果factorizecallback是一個需要同步化/線成親和上下文的上下文綁定類,那么回調被通過上下文分配體系結構來分配。換句話說,相對于它的對這樣的上下文的調用者,回調可能異步的執行。在方法標記上有單向修飾詞的精確的語義。這指的是任何這樣的方法調用可能同步地或異步地執行,相對于調用者,并且在執行控制返回給它的時候,調用者不能產生任何關于完成這樣一個調用的假設。
而且,在異步操作完成之前調用endinvoke將阻塞調用者。使用相同的asyncresult再次調用它的行為是不確定的。
cancel方法是一個在過去一段特定時間之后取消方法處理的請求。注意它是一個客戶端的請求,并且最好服務器對此有所承諾。在接收到方法已經被取消的消息之后,客戶端就不必做服務器是否已經停止處理的假設了。客戶端最好不要破壞資源,例如文件對象,因為服務器可能仍然需要使用它們。iasyncresult實例的iscompleted屬性在服務器結束它的處理之后將被設置為true,不再使用任何客戶端提供的資源。因此,iscompleted屬性設置為true之后,客戶端就可以安全的銷毀資源了。
 
新聞熱點
疑難解答
圖片精選