C # Introduction to delegated asynchronous calls

Source: Internet
Author: User
C # Introduction to delegated asynchronous calls

(18:13:06)

{
Scope. articel_quote_alert & scope. articel_quote_alert ('674f71e30100hpxt '); Return false;
} "Href =" javascript:; "> Reprinted
C-delegate asynchronous call  

The following descriptions are excerpted from msdn:

Asynchronous delegation provides the ability to call synchronous Methods asynchronously.

When the delegate is synchronously called, The invoke () method directly calls the target method to the current thread;

When a delegate is called asynchronously, CLR queues the request and immediately returns it to the caller. This method is called for the thread from the thread pool, the original thread that submits the request continues to run in parallel with the target method, which runs on the thread pool thread.

1) begininvoke () method

The begininvoke () method starts asynchronous calls. It has the same parameters as the method to be asynchronously executed.

In addition, there are two optional parameters: the first parameter is the asynccallback delegate, which references the method to be called when the asynchronous call is complete; the second parameter is the User-Defined Object, this object can pass information to the callback method;

Begininvoke returns immediately without waiting for the asynchronous call to complete;

Begininvoke returns iasyncresult, which can be used to monitor the progress of asynchronous calls;

2) endinvoke () method

The endinvoke () method is used to retrieve the asynchronous call results;

After the begininvoke () method is called, you can call the endinvoke () method at any time. If the asynchronous call is not completed, the endinvoke () method will always stop the calling thread, the invocation thread is not allowed until the asynchronous call is complete;

The parameters of endinvoke () require the out and ref parameters of the Asynchronous Method and the iasyncresult returned by begininvoke.

The following code describes asynchronous delegation:

Code 1: Synchronous execution:
Public Delegate int mathdelegate (int x );
Public class mathclass
{
Public int add (int x)
{
Thread. Sleep (10000); // simulate a task that has been executed for a long time.
Return x + X;
}
}

Public class Program
{
Public static void main (string [] ARGs)
{
Mathclass addclass = new mathclass ();
Mathdelegate mathdel = new mathdelegate (addclass. Add );

// Synchronous execution
Int syncresult = mathdel (8 );
Console. writeline ("Sync proccessing operation..."); // This line can only be displayed after syncmethod is complete.
Console. writeline ("Sync result is: {0}", syncresult );

Console. Readline ();
}
}
When the program runs to int syncresult = mathdel (8);, the main thread will wait for at least 10 seconds (the execution of the add method) before execution.
The subsequent code, that is, during which the application does not respond and cannot perform any other operations until the add method returns the result.
Code 2: asynchronous execution:

Let's slightly modify the main code:

Public static void main (string [] ARGs)
{
Mathclass addclass = new mathclass ();
Mathdelegate mathdel = new mathdelegate (addclass. Add );

Iasyncresult async = mathdel. begininvoke (9, null, null); // call the add method in another thread.
Console. writeline ("async proccessing operation..."); // print it to the terminal device immediately
Int asyncreuslt = mathdel. endinvoke (async );
Console. writeline ("result is: {0}", asyncreuslt );

Console. Readline ();
}

In this Code, the begininvoke () method is not directly called at the beginning, but the iasyncresult object is returned.

Code 3: iscompleted. Round Robin asynchronous call is complete.Use the iscompleted attribute of the iasyncresult instance to obtain the indication of whether the asynchronous operation has been completed. If the operation is completed, it is true; otherwise, it is false.

Modify the main code:

Public static void main (string [] ARGs)
{
Mathclass addclass = new mathclass ();
Mathdelegate mathdel = new mathdelegate (addclass. Add );

Iasyncresult async = mathdel. begininvoke (9, null, null); // call the add method in another thread.
Console. writeline ("async proccessing operation..."); // print it to the terminal device immediately

Int I = 1;
While (async. iscompleted = false)
{
Thread. Sleep (I * 1000 );
Console. writeline ("iscompleted: {0}, {1}", async. iscompleted, I );
I ++;
}
Int asyncreuslt = mathdel. endinvoke (async );
Console. writeline ("result is: {0}", asyncreuslt );

Console. Readline ();
}
Code 4: asynccallback. The callback method is executed when the asynchronous call is complete.

If the thread that starts the asynchronous call does not need to be the thread that processes the result, the callback method can be executed when the call is complete;

If you want to use the callback method, you must delegate the referenced callback method asynccallback to the begininvoke () method, or pass the object containing the information to be used by the callback method.

Modify the main code:

Public static void main (string [] ARGs)
{
Mathclass addclass = new mathclass ();
Mathdelegate mathdel = new mathdelegate (addclass. Add );

Iasyncresult async = mathdel. begininvoke (9, new asynccallback (completemethod), "information comes from the main thread"); // in another thread, call the Add Method
Console. writeline ("async proccessing operation..."); // print it to the terminal device immediately
Console. Readline ();
}
Private Static void completemethod (iasyncresult async)
{
Asyncresult AR = (asyncresult) async;

Mathdelegate del = (mathdelegate) Ar. asyncdelegate;
Int result = del. endinvoke (async );

String maintheadmsg = ar. asyncstate as string;
Console. writeline ("{0}, result is: {1}", maintheadmsg, result );
}

 

After the add method is called, call the completemethod method.
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.