Simple asynchronous Web method
To illustrate asynchronous Web methods, I started with a simple synchronous Web method named LengthyProcedure. The Code is as follows. Then let's take a look at how to complete the same task asynchronously. LengthyProcedure only takes a specified number of milliseconds.
[WebService]
Public class SyncWebService: System. Web. Services. WebService
{
[WebMethod]
Public string LengthyProcedure (int milliseconds)
{
System. Threading. Thread. Sleep (milliseconds );
Return "successful ";
}
}
Now we can convert LengthyProcedure to an asynchronous Web method. We must create the BeginLengthyProcedure function and EndLengthyProcedure function as described above. Remember that an IAsyncResult interface is returned for our BeginLengthyProcedure call. Here, I plan to use a delegate and the BeginInvoke method on the delegate to make our BeginLengthyProcedure call Asynchronous Method call. The callback function passed to BeginLengthyProcedure will be passed to the ininvoke method on the delegate, and the IAsyncResult returned from BeginInvoke will be returned by the BeginLengthyProcedure method.
When the delegate is completed, the EndLengthyProcedure method is called. We will call the EndInvoke method on the delegate to pass in IAsyncResult and use it as the input for the EndLengthyProcedure call. The returned string is the string returned from the Web method. The following is 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 "successful ";
}
Public class MyState
{
Public object previusstate;