首页 > 编程 > .NET > 正文

ASP.NET创建Web服务之异步Web服务

2024-07-10 13:06:00
字体:
来源:转载
供稿:网友

为了改善调用阻碍线程的长期运行的方法的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之后,客户端就可以安全的销毁资源了。


 

国内最大的酷站演示中心!
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表