Matt Powell's "Server-side Asynchronous Web Methhods"

Source: Internet
Author: User
Tags functions httpcontext net sleep string thread web services visual studio
server|web| Asynchronous | Asynchronous Summary: Matt Powell Describes how to use asynchronous Web methods on the server side to create high-performance Microsoft asp.net Web services.

Brief introduction

In the third column in September (in English), I talked about the issue of invoking Web services asynchronously via HTTP with the client features of the Microsoft. NET Framework. This method of invoking Web services is useful, and you do not have to lock your application or generate too many background threads when you use it. Now let's look at asynchronous Web methods that provide similar functionality on the server side.   Asynchronous Web methods have a high performance similar to the hse_status_pending approach in writing ISAPI extensions, but do not need to write code for managing their own thread pools, while having all the benefits of running in managed code. First, let's consider the regular sync Microsoft? ASP.net Web methods. When you return from the synchronization Web method, a response to the method is sent. If a longer time is required to complete the request, the thread that processes the request is occupied until the method call is finished. Unfortunately, most of the longer calls are caused by long database queries or calls to another Web service. For example, if you call a database, the current thread waits for the call to complete. Threads have nothing to do, just wait until they hear the query return. Similar problems can occur when a thread waits to complete a call to a TCP socket or back-end Web service.

It's not good to keep the thread waiting, especially if the server is under a lot of pressure. Threads in wait will not perform any effective work, such as servicing other requests. We need to find a way to start a long background process on the server while returning the current thread to the asp.net process pool. Then, when the long background process completes, we call a callback function, end the processing of the request, and somehow notify the asp.net that the request has been completed. In fact, this functionality can be provided by ASP.net using asynchronous Web methods.

How asynchronous Web methods work

When you write a typical asp.net Web service using Web methods, Microsoft? Visual Studio?. Net simply compiles your code to create the assembly, which is called when a request to its Web method is received. The assembly itself does not know anything about SOAP. Therefore, when your application starts for the first time, the ASMX handler must reflect your assembly to determine which WEB methods are provided. For general synchronization requests, these operations are simple: Find out which methods have the associated WebMethod property, and set the logic for invoking the correct method based on the SOAPAction HTTP header.

For asynchronous requests, in the reflection process, the ASMX handler looks for WEB methods that have some kind of signature and recognize the signature as asynchronous. The handler will look for a method pair that meets the following rules:

BeginXXX and EndXxx Web methods, where XXX is any string that represents the name of the method to be provided.
The BeginXXX function returns a IAsyncResult interface and accepts AsyncCallback and an object, respectively, as its last two input parameters.
The ENDXXX function accepts a IAsyncResult interface as its only parameter.

All two methods must be identified by using the WebMethod property.

If the ASMX handler finds that two methods meet all of the above criteria, the method XXX is provided in its WSDL as a regular Web method. The method will accept the parameter defined before the AsyncCallback parameter in the BeginXXX signature as input and return the content returned by the ENDXXX function. Therefore, if a Web method has the following synchronization declaration:



[WebMethod]
public string LengthyProcedure (int milliseconds) {...}





The asynchronous declaration will be:




[WebMethod]
Public IAsyncResult BeginLengthyProcedure (
int milliseconds,
AsyncCallback CB,
Object s) {...}

[WebMethod]
public string EndLengthyProcedure (IAsyncResult call) {...}





The WSDL for each method is the same.

After an ASMX handler reflects an assembly and detects an asynchronous Web method, it must handle a request to that method in a different way than to handle the synchronization request. It calls the BeginXXX method, not some simple method. It serializes the incoming request restore to the parameter to be passed to the function (as in the case of the synchronization request), but it also passes the pointer to an internal callback function (as an additional AsyncCallback parameter for the BeginXXX method).

This approach is similar to the asynchronous programming pattern for WEB service client applications in the. NET Framework. If the client supports asynchronous Web service calls, you can release the thread that is occupied for the client computer, and if the server side supports asynchronous Web service calls, you can free the threads that are occupied on the server computer. But here are two key differences. First, the BeginXXX and ENDXXX functions are not called by server code, but are called by the ASMX handler. Second, you write code for the BeginXXX and ENDXXX functions, and you can't use the WSDL. EXE or code generated by the Add Web Reference (adding Web References) Wizard in Visual Studio. NET. But the result is the same, freeing the thread so that it can perform other processes.

When the ASMX handler calls the server's BeginXXX function, it returns the thread to the process thread pool so that it can handle any other requests received. However, you cannot release the requested HttpContext. The ASMX handler waits until the callback function passed to the BeginXXX function is invoked to end the processing request.

Once the callback function is invoked, the ASMX handler calls the ENDXXX function so that your Web method can perform any processing you want, and you can get the return data that is serialized into the SOAP response. When the EndXxx function returns, the response is sent and only the HttpContext of the request is released.







A simple asynchronous Web method

To illustrate asynchronous Web methods, I start with a simple synchronous Web method called LengthyProcedure, whose code looks like this. Then we'll look at how to do the same task asynchronously. LengthyProcedure only takes a given number of milliseconds.



[WebService]
public class SyncWebService:System.Web.Services.WebService
{
[WebMethod]
public string LengthyProcedure (int milliseconds)
{
System.Threading.Thread.Sleep (milliseconds);
Return "Success";
}
}





Now we convert LengthyProcedure to asynchronous Web methods. We must create the BeginLengthyProcedure function and the EndLengthyProcedure function as described earlier. Keep in mind that our beginlengthyprocedure call needs to return a IAsyncResult interface. Here, I intend to use a delegate and the BeginInvoke method on the delegate to let our BeginLengthyProcedure call make an asynchronous method call. The callback function passed to BeginLengthyProcedure will be passed to the BeginInvoke method on the delegate, and the IAsyncResult returned from BeginInvoke will be returned by the BeginLengthyProcedure method.

When the delegate completes, the EndLengthyProcedure method is invoked. We will invoke the EndInvoke method on the delegate to pass in the IAsyncResult as input to the endlengthyprocedure call. The returned string will be the string returned from the Web method. Here's the code:




[WebService]
public class AsyncWebService:System.Web.Services.WebService
{
Public delegate String LengthyProcedureAsyncStub (
int milliseconds);

public string LengthyProcedure (int milliseconds)
{
System.Threading.Thread.Sleep (milliseconds);
Return "Success";
}

public class MyState
{
public object previousstate;
Public LengthyProcedureAsyncStub asyncstub;
}

[System.Web.Services.WebMethod]
Public IAsyncResult beginlengthyprocedure (int milliseconds,
AsyncCallback cb, Object s)
{
LengthyProcedureAsyncStub stub
= new LengthyProcedureAsyncStub (lengthyprocedure);
MyState ms = new MyState ();
Ms.prev



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.