Sometimes, when we want to request a large amount of data from some external devices or networks, the external devices may need to process the data for a long time before it can be transferred back to the computer. At this time, we just have a silly wait.
However, the Asynchronous Method of callback is different. We can use this time to do other things. After waiting, we will be notified.
1. How to Make asynchronous calls
(1) define the method to run Asynchronization.
(2) define a trust with the same signature as running the Asynchronous Method.
(3) instantiate the trust. The trust should point to the Asynchronous Method.
(4) use begininvoke to start the Asynchronous Method.
(5) Use endinvoke to obtain the result.
(6) set the callback method. (Not required)
2. Use of begininvoke and endinvoke methods:
We all know that when a program defines a commitment, the common language execution library will automatically define the signed beginvoke and endinvoke methods for this commitment.
(1) begininvoke
The begininvoke method is used to start asynchronous calls. It has the same number of arguments as the method you need to run asynchronously, and there are two additional arguments.
Begininvoke indicates to return immediately without waiting for the completion of asynchronous call.
Begininvoke returns an iasyncresult that can be used to monitor asynchronous progress.
(2) endinvoke
The endinvoke method is used to retrieve asynchronous call results. After begininvoke is called, you can call the endinvoke method at any time. If the asynchronous call is not completed, endinvoke will remain congested.
Asynchronous call is complete. The number of endpoints of endinvoke includes the number of out and ref partitions of the methods to be run asynchronously (<out> byref and byref in Visual Basic) and the iasyncresult returned by begininvoke.
3. Demo:
Namespace consoleapplication
{
// Define the proxy
Delegate string mydelegate ();
Class temp
{
Static void main (string [] ARGs)
{
// Instantiate the proxy
Mydelegate MD = new mydelegate (asyncmethod );
// A callback proxy for the instance
Asynccallback callback = new asynccallback (callbackmethod );
// Start the Asynchronous Method
Md. begininvoke (callback, MD );
Console. Readline ();
}
// Asynchronous call Method
Static string asyncmethod ()
{
Console. writeline ("Asynchronous Method is running ");
String STR = "Asynchronous call ended ";
Return STR;
}
// Callback Method
Static void callbackmethod (iasyncresult IAS)
{
Mydelegate MD = (mydelegate) IAS. asyncstate;
String STR = md. endinvoke (IAS );
Console. writeline (STR );
}
}
}