C # example of asynchronous call

Source: Internet
Author: User

Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. Threading;
Using system. Windows. forms;

Namespace CW
{

Public partial class asyncdemo: Form
{
Public asyncdemo ()
{
Initializecomponent ();
}

Private void delgate_load (Object sender, eventargs E)
{

}

/// <Summary>
/// Delegate Method
/// </Summary>
/// <Param name = "icalltime"> </param>
/// <Param name = "iexecthread"> </param>
/// <Returns> </returns>
String longrunningmethod (INT icalltime, out int iexecthread)
{
Thread. Sleep (icalltime );
Iexecthread = appdomain. getcurrentthreadid ();
Return "mycalltime was" + icalltime. tostring ();
}

Delegate string methoddelegate (INT icalltime, out int iexecthread );

# region Example 1: Synchronous call method # region Example 1: synchronous call method
/**/
/*
* synchronous call method
**/
// /


// Example 1: synchronous call method
//
Public void demosynccall ()
{< br> string s;
int iexecthread;

// Create an instance of a delegate that wraps longrunningmethod.
Methoddelegate dlgt = new methoddelegate (this. longrunningmethod );

// Call longrunningmethod using the delegate.
S = dlgt (3000, out iexecthread );

MessageBox. Show (string. Format ("the delegate call returned the string: {0}, and the thread ID {1}", S, iexecthread. tostring ()));

}
# Endregion

# Region Example 2: asynchronous call method through endinvoke () call mode
/**/
/*
* In the call mode, you need to call begininvoke to process the main thread and call endinvoke ().
* Note that no endinvoke () is returned until the asynchronous call is completed.
* This call mode is useful when a call thread is executing an asynchronous call and working simultaneously.
* Multiple applications can be improved when work occurs at the same time. Program Performance.
* Common Tasks run asynchronously in this mode as file or network operations.
**/
/**/
/// <Summary>
/// Example 2: Use endinvoke () to call the method asynchronously.
/// </Summary>
Public void demoendinvoke ()
{
Methoddelegate dlgt = new methoddelegate (this. longrunningmethod );
String S;
Int iexecthread;

// Initiate the asynchronous call.
Iasyncresult AR = dlgt. begininvoke( 5000, out iexecthread, null, null );

// Do some useful work here. This wocould be work you want to have
// Run at the same time as the asynchronous call.

// Retrieve the results of the asynchronous call.
S = dlgt. endinvoke (Out iexecthread, AR );

MessageBox. Show (string. Format ("the delegate call returned the string: {0}, and the number {1}", S, iexecthread. tostring ()));
}
# Endregion

# Region Example 3: Call the method asynchronously and use a waithandle to wait for the call to complete
/**/
/*
* The iasyncresult returned by begininvoke () has an asyncwaithandle attribute.
* After the waithandle asynchronous call is returned for this attribute, the notification is yes. Waiting for waithandle is a common thread synchronization technology.
* The waithandle waitone () method is used to call the thread and wait for the waithandle.
* The waithandle waitone () block is notified. When waitone () is returned, you do some additional work before calling endinvoke.
* This technique is useful in previous examples for executing file or network operations, otherwise it will block the calling of the main thread.
**/
/**/
/// <Summary>
/// Example 3: Call the method asynchronously and use a waithandle to wait until the call is completed.
/// </Summary>
Public void demowaithandle ()
{
String S;
Int iexecthread;

Methoddelegate dlgt = new methoddelegate (this. longrunningmethod );

// Initiate the asynchronous call.
Iasyncresult AR = dlgt. begininvoke( 3000, out iexecthread, null, null );

// Do some useful work here. This wocould be work you want to have
// Run at the same time as the asynchronous call.

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

// Get the results of the asynchronous call.
S = dlgt. endinvoke (Out iexecthread, AR );

MessageBox. Show (string. Format ("the delegate call returned the string: {0}, and the number {1}", S, iexecthread. tostring ()));
}
# Endregion

# Region Example 4: asynchronous call method round-robin call mode
/**/
/*
* If the iasyncresult object returned by begininvoke () has an iscompleted attribute, return true after the asynchronous call is completed.
* You can call endinvoke (). This call mode is useful if your application continues to work and does not require long-term function calls.
* The microsoftwindows application is used as an example.
* Windows applications in the main thread can continue to process user input for asynchronous calls.
* It regularly checks whether the iscompleted call is complete. It calls endinvoke and returns true when iscompleted.
* Until it knows that the operation is completed because endinvoke () is blocked until the asynchronous operation is complete, the application does not call it.
**/
/**/
/// <Summary>
/// Example 4: asynchronous call method round-robin call mode
/// </Summary>
Public void demopolling ()
{
Methoddelegate dlgt = new methoddelegate (this. longrunningmethod );
String S;
Int iexecthread;

// Initiate the asynchronous call.
Iasyncresult AR = dlgt. begininvoke( 3000, out iexecthread, null, null );

// Poll iasyncresult. iscompleted
While (AR. iscompleted = false)
{
Thread. Sleep (10); // pretend to so some useful work
}
S = dlgt. endinvoke (Out iexecthread, AR );

MessageBox. Show (string. Format ("the delegate call returned the string: {0}, and the number {1}", S, iexecthread. tostring ()));
}
# Endregion

# Region Example 5: Execute callback after the Asynchronous Method is completed
/**/
/*
* In this section, the begininvoke () function is used as an example. After the asynchronous call is completed, the system executes the callback delegate.
* Calls the endinvoke () callback and processes the asynchronous call results.
* This call mode is useful if the asynchronous call thread is started and does not need to process the result.
* After the asynchronous call is completed, the startup thread outside the system call thread is raised.
* If this call mode is used, the asynccallback type delegate must be passed as the parameter of the second-to-last-begininvoke () function.
* Begininvoke () also has the final parameter input object to which you can set any object. When it calls this object, it can be used for your callback function.
* An important purpose of this parameter is to pass it for initializing and calling the delegate.
* The callback function is then called using the delegate endinvoke () function. This call mode is shown in.
**/
/**/
/// <Summary>
/// Example 5: The callback is executed after the Asynchronous Method is complete.
/// </Summary>
Public void democallback ()
{
Methoddelegate dlgt = new methoddelegate (this. longrunningmethod );
Int iexecthread;

// Create the callback delegate.
Asynccallback cb = new asynccallback (myasynccallback );

// Initiate the asynchronous call passing in the callback delegate
// And the delegate object used to initiate the call.
Iasyncresult AR = dlgt. begininvoke( 5000, out iexecthread, CB, dlgt );
}

Public void myasynccallback (iasyncresult AR)
{
String S;
Int iexecthread;

// Because you passed your original delegate in the asyncstate Parameter
// Of The begin call, you can get it back here to complete the call.
Methoddelegate dlgt = (methoddelegate) Ar. asyncstate;

// Complete the call.
S = dlgt. endinvoke (Out iexecthread, AR );
MessageBox. Show (string. Format ("the delegate call returned the string: {0}, and the number {1}", S, iexecthread. tostring ()));

// console. writeline (string. format ("the delegate call returned the string:" {0} ", and the number {1}", S, iexecthread. tostring ();
}< BR ># endregion

private void button#click (Object sender, eventargs e)
{< br> // demosynccall ();
// demoendinvoke ();
// demowaithandle ();
// demopolling ();
democallback ();
}< BR >}

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.