Simple asynchronous web method
For an exemplary web method, I started from a simple synchronization web method called Length, and its code is as follows. Then we look at how to make the same task asynchronously. LengthyProcedure only occupies a given millisecond.
[WebService]
Public Class SyncWebService: System.Web.Services.Webservice
{
[WebMethod]
Public string lengthprocedure (int MilliseConds)
{
System.threading.thread.sleep (MilliseConds);
Return "success";
}
}
Now we convert LengthyProcedure to an asynchronous web method. We must create the BeginLengthyProcedure function and endlengthyprocedure functions as described above. Keep in mind that our BeginLengthyProcedure call needs to return an IASYNCRESULT interface. Here, I intend to use a delegate and the BeginInvoke method on the commission, let our BeginLengthyProcedure call for asynchronous method calls. The callback function passing to the BeginLengthProcedure will be passed to the BeginInvoke method on the commission, and the IASYNCRESULT returned from BeGinInvoke will be returned by the BeginLength Procedure method.
The endlengthyprocedure method will be called when the commission is completed. We will call the EndInvoke method on the commission to pass it into the IASYNCRESULT and use it as an input called endlengthyprocedure. The returned string will be a string returned from the web method. Below is its code:
[WebService]
Public Class AsyncWebService: System.Web.Services.Webservice
{
Public delegate string lengthprocedureasyncstub
INT MilliseConds;
Public string lengthprocedure (int MilliseConds)
{
System.threading.thread.sleep (MilliseConds);
Return "success";
}
Public class myState
{
Public Object PreviouState;
Public longthyprocedureasyncstub asyncstub;
}
[System.web.services.webmethod]
Public IASYNCRESULT BEGINLENGTHYPROCEDURE (Int Milliseconds,
AsyncCallback CB, Object S)
{
Lengthyprocedureasyncstub stub
= New lengthProcedureAsyncStub (lengthprocedure);
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);
}
}