Asynchronous programming Overview

Source: Internet
Author: User
NET framework allows you to call any method asynchronously. Define the delegate with the same signature as the method to be called. The Common Language Runtime automatically defines the delegate with the appropriate Signature Begininvoke And Endinvoke Method.

BegininvokeMethod is used to start asynchronous calls. It has the same parameters as the method to be asynchronously executed, but there are two additional parameters (which will be described later ).BegininvokeReturn immediately without waiting for the asynchronous call to complete.BegininvokeIasyncresult is returned, which can be used to monitor the call progress.

EndinvokeThe method is used to retrieve asynchronous call results. CallBegininvokeCan be called at any timeEndinvokeMethod; if the asynchronous call is not completed,EndinvokeIt will be blocked until the asynchronous call is completed.EndinvokeParameters includeOutAndRefParameter (<out> in Visual BasicByrefAndByref) AndBegininvokeReturnedIasyncresult.

Note:The smart sensing function in Visual Studio. NET is displayed.BegininvokeAndEndinvoke. If you do not use Visual Studio or similar tools, or you are using C # and Visual Studio. for more information, see Asynchronous Method signature to obtain descriptions of parameters defined by the runtime for these methods.

In this topicCodeDemonstrate four types of useBegininvokeAndEndinvokeA common method for asynchronous calling. CalledBegininvokeYou can:

    • And then callEndinvokeUntil the call is complete.
    • Use iasyncresult. asyncwaithandle to obtain waithandle, and use its waitone method to block the execution until it is issuedWaithandleSignal, then callEndinvoke.
    • PollingBegininvokeReturnedIasyncresultDetermine when the asynchronous call is completed, and then callEndinvoke.
    • Pass the delegate used for the callback methodBegininvoke. This method is executed on the threadpool thread after the asynchronous call is completed. It can callEndinvoke.

      WarningAlways call after asynchronous call is completeEndinvoke.

Test method and asynchronous Delegation

The four examples all use the same long-term running test method.Testmethod. This method displays a console information indicating that it has started processing. It is dormant for several seconds and then ended.TestmethodThere isOutParameter (<out> in Visual BasicByref), It demonstrates how to add these parametersBegininvokeAndEndinvoke. You can handle it in a similar way.RefParameter (in Visual BasicByref).

The following code example showsTestmethodAnd representativesTestmethodTo use any example, append the sample code to this section.

Note:To simplify these examples,TestmethodInMain (). Or,TestmethodIt can be includeMain ()In the same classStaticMethod (in Visual BasicShared).

 

Using system;
Using system. Threading;

Public class asyncdemo {
// The method to be executed asynchronously.
//
Public String testmethod (INT callduration, out int threadid ){
Console. writeline ("test method begins .");
Thread. Sleep (callduration );
Threadid = appdomain. getcurrentthreadid ();
Return "mycalltime was" + callduration. tostring ();
}
}

// The delegate must have the same signature as the method
// You want to call asynchronously.
Public Delegate string asyncdelegate (INT callduration, out int threadid );
Use endinvoke to wait for asynchronous call

The simplest method for asynchronous execution isBegininvokeStart, execute some operations on the main thread, and then callEndinvoke.EndinvokeIt is not returned until the asynchronous call is complete. This technology is very suitable for file or network operations, but it is blockedEndinvokeSo do not use it from the service thread on the user interface.


Public class asyncmain {
Static void main (string [] ARGs ){
// The Asynchronous Method puts the thread ID here.
Int threadid;

// Create an instance of the test class.
Asyncdemo ad = new asyncdemo ();

// Create the delegate.
Asyncdelegate dlgt = new asyncdelegate (Ad. testmethod );

// Initiate the Asychronous call.
Iasyncresult AR = dlgt. begininvoke( 3000,
Out threadid, null, null );

Thread. Sleep (0 );
Console. writeline ("main thread {0} does some work .",
Appdomain. getcurrentthreadid ());

// Call endinvoke to wait for the asynchronous call to complete,
// And to retrieve the results.
String ret = dlgt. endinvoke (Out threadid, AR );

Console. writeline ("the call executed on thread {0}, with return value" "{1}" ".", threadid, RET );
}
}
Use waithandle to wait for asynchronous call

Waiting for waithandle is a common thread synchronization technology. You can useBegininvokeThe returned iasyncresult's asyncwaithandle attribute to obtainWaithandle. When the asynchronous call is completedWaithandleAnd you can wait for it by calling its waitone.

If you useWaithandleAfter the asynchronous call is completedEndinvokeYou can perform other operations before retrieving results.


Public class asyncmain {
Static void main (string [] ARGs ){
// The Asynchronous Method puts the thread ID here.
Int threadid;

// Create an instance of the test class.
Asyncdemo ad = new asyncdemo ();

// Create the delegate.
Asyncdelegate dlgt = new asyncdelegate (Ad. testmethod );

// Initiate the Asychronous call.
Iasyncresult AR = dlgt. begininvoke( 3000,
Out threadid, null, null );

Thread. Sleep (0 );
Console. writeline ("main thread {0} does some work .",
Appdomain. getcurrentthreadid ());

// Wait for the waithandle to become signaled.
Ar. asyncwaithandle. waitone ();

// Perform additional processing here.
// Call endinvoke to retrieve the results.
String ret = dlgt. endinvoke (Out threadid, AR );

Console. writeline ("the call executed on thread {0}, with return value" "{1}" ".", threadid, RET );
}
}
Round Robin asynchronous call completed

You can useBegininvokeThe iscompleted attribute of the returned iasyncresult to find out when the asynchronous call is completed. This operation can be performed when asynchronous calling is performed from the service thread on the user interface. After the round robin is completed, the user interface thread can continue to process user input.

 

Public class asyncmain {
Static void main (string [] ARGs ){
// The Asynchronous Method puts the thread ID here.
Int threadid;

// Create an instance of the test class.
Asyncdemo ad = new asyncdemo ();

// Create the delegate.
Asyncdelegate dlgt = new asyncdelegate (Ad. testmethod );

// Initiate the Asychronous call.
Iasyncresult AR = dlgt. begininvoke( 3000,
Out threadid, null, null );

// Poll While simulating work.
While (AR. iscompleted = false ){
Thread. Sleep (10 );
}

// Call endinvoke to retrieve the results.
String ret = dlgt. endinvoke (Out threadid, AR );

Console. writeline ("the call executed on thread {0}, with return value" "{1}" ".", threadid, RET );
}
}
Callback method executed when asynchronous call is complete

If the thread that starts the asynchronous call does not need to process the call result, You can execute the callback method when the call is completed. The callback method is executed on the threadpool thread.

To use the callback method, the asynccallback delegate representing the method must be passedBegininvoke. You can also pass the object that contains the information to be used by the callback method. For example, you can pass the delegate that was used when the call was started so that the callback method can be called.Endinvoke.


Public class asyncmain {
// Asynchronous Method puts the thread ID here.
Private Static int threadid;

Static void main (string [] ARGs ){
// Create an instance of the test class.
Asyncdemo ad = new asyncdemo ();

// Create the delegate.
Asyncdelegate dlgt = new asyncdelegate (Ad. testmethod );

// Initiate the Asychronous call. Include an asynccallback
// Delegate representing the callback method, and the data
// Needed to call endinvoke.
Iasyncresult AR = dlgt. begininvoke( 3000,
Out threadid,
New asynccallback (callbackmethod ),
Dlgt );

Console. writeline ("press enter to close application .");
Console. Readline ();
}

// Callback method must have the same signature as
// Asynccallback delegate.
Static void callbackmethod (iasyncresult AR ){
// Retrieve the delegate.
Asyncdelegate dlgt = (asyncdelegate) Ar. asyncstate;

// Call endinvoke to retrieve the results.
String ret = dlgt. endinvoke (Out threadid, AR );

Console. writeline ("the call executed on thread {0}, with return value" "{1}" ".", threadid, RET );
}
}

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.