Asp. NET Server-side asynchronous Web method

Source: Internet
Author: User
Tags call back httpcontext sleep socket stub thread web services visual studio
asp.net|web| Server | 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 (English), I talked about the issue of using the Microsoft¡.net Framework's client capabilities to invoke Web services asynchronously via HTTP. 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 we consider the regular synchronous microsoft¡asp.net Web approach. 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 you receive a request for its Web method. 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.previousstate = s;
ms.asyncstub = stub;
return stub. BeginInvoke (milliseconds, CB, MS);
}

[System.Web.Services.WebMethod]
public string EndLengthyProcedure (IAsyncResult call)
{
MyState ms = (mystate) call.asyncstate;
Return Ms.asyncStub.EndInvoke (call);
}
}

When to adopt an asynchronous Web method

There are a few issues to consider when determining whether it is appropriate to adopt an asynchronous Web method in your application. First, the called BeginXXX function must return a IAsyncResult interface. IAsyncResult are returned from multiple asynchronous I/O operations, including accessing the data stream, making microsoft¡windows¡ socket calls, performing file I/O, interacting with other hardware devices, invoking asynchronous methods, and of course invoking other WEB services. You can get IAsyncResult from these asynchronous operations to return it from the BeginXXX function. You can also create your own classes to implement the IAsyncResult interface, but you may then need to wrap some of the previously mentioned I/O operations in some way.

For most asynchronous operations mentioned earlier, it makes sense to use asynchronous Web methods to wrap back-end asynchronous calls, making Web service code more efficient. Except when using a delegate to make an asynchronous method call. Delegates cause asynchronous method calls to occupy a thread in the process thread pool. Unfortunately, the ASMX handler also uses these threads when servicing incoming requests. So unlike calls to perform real I/O operations on hardware or network resources, asynchronous method calls that use delegates will still occupy one of the process threads while executing. You can also use the original thread to run your Web methods synchronously.

The following example shows an asynchronous Web method that invokes a back-end Web service. It has identified the Begingetage and Endgetage methods using the WebMethod property to run asynchronously. The code for this asynchronous Web method calls the back-end Web method named Userinfoquery to get the information it needs to return. Calls to the Userinfoquery are executed asynchronously and are passed to the AsyncCallback function, which is passed to the Begingetage method. This will cause the internal callback function to be invoked when the backend request completes. The callback function then calls the Endgetage method to complete the request. The code in this example is much simpler than the code in the previous example, and has another advantage, that is, it does not start back-end processing in the same thread pool that serves the middle-tier Web method request.

[WebService]
public class GetMyInfo:System.Web.Services.WebService
{
[WebMethod]
Public IAsyncResult Begingetage (AsyncCallback cb, Object State)
{
Invokes an asynchronous Web service call.
localhost. Userinfoquery Proxy
= new localhost. Userinfoquery ();
Return proxy. Begingetuserinfo ("username",
Cb
proxy);
}

[WebMethod]
public int Endgetage (IAsyncResult res)
{
localhost. Userinfoquery Proxy
= (localhost. Userinfoquery) Res.asyncstate;
int age = Proxy. Endgetuserinfo (RES). Age;
The results of this WEB service are otherwise
Processing.
return age;
}
}

One of the most common types of I/O operations that occurs in a Web method is a call to an SQL database. Unfortunately, Microsoft¡ado.net has not yet defined a good asynchronous invocation mechanism, and simply wrapping the SQL calls into asynchronous delegate invocations has little to do with improving efficiency. Although you can sometimes choose to cache results, you should also consider using Microsoft SQL Server Web Services Toolkit to publish your database as a Web service. This enables you to invoke the Web service asynchronously to query or update the database, using the support in the. NET Framework.

When accessing SQL through a WEB service invocation, you need to be aware of many back-end resources. If you use a TCP socket to communicate with a Unix computer, or access a few other available SQL platforms through a dedicated database driver, or even a resource that is accessed using DCOM, you can consider using a number of Web services toolkits to publish these resources as Web services.

One of the advantages of using this approach is that you can take advantage of the client Web service architecture, such as asynchronous Web service calls that use the. NET Framework. This allows you to get asynchronous invocation capabilities for free, and your client access mechanism works efficiently with asynchronous Web methods.

Aggregating data using asynchronous Web methods

Many Web services now access multiple resources at the back end and aggregate information for the front-end Web services. Although invoking multiple back-end resources increases the complexity of the asynchronous Web method model, it can ultimately improve efficiency significantly.

Suppose your Web method calls two back-end Web services: Service A and service B. From your BeginXXX function, you can invoke service A and service B asynchronously. You should pass your own callback function to each asynchronous call. After receiving the results from service A and service B, the callback function that you provide to trigger the completion of the Web method verifies that all requests have been completed, that all the processing is done on the returned data, and then calls the callback function passed to the BeginXXX function. This will trigger a call to the ENDXXX function, which will result in the completion of the asynchronous Web method.

Summary

Asynchronous Web methods provide an efficient mechanism in asp.net Web services to call back-end services without taking advantage of valuable threads in the process thread pool. By combining asynchronous requests for back-end resources, the server can use its own WEB methods to maximize the number of simultaneous requests processed. You should consider using this method to develop High-performance Web service applications.



Related Article

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.