C # Delegate asynchronous call,

Source: Internet
Author: User

C # Delegate asynchronous call,

This article will mainly explain the differences and advantages and disadvantages of using the "synchronous call", "Asynchronous call", and "Asynchronous callback" to execute the same "addition class" with a delegate.
 

First, use the code to define a delegate and the methods to be called in the following three examples:

/* Added namespace
Using System. Threading;
Using System. Runtime. Remoting. Messaging;
*/
Public delegate int AddHandler (int a, int B );
Public class addition class
{
Public static int Add (int a, int B)
{
Console. WriteLine ("START calculation:" + a + "+" + B );
Thread. Sleep (3000); // simulate this method for three seconds
Console. WriteLine ("computing completed! ");
Return a + B;
}
}

 

 

Synchronous call

The entrusted Invoke method is used for Synchronous calling. Synchronous call can also be called blocking call. It will block the current thread and then execute the call. After the call is completed, continue to the next step.

Synchronous call of public class
{
Static void Main ()
{
Console. WriteLine ("===== synchronously call SyncInvokeTest ==== ");
AddHandler handler = new AddHandler (addition class. Add );
Int result = handler. Invoke (1, 2 );

Console. WriteLine ("continue to do other things... ");

Console. WriteLine (result );
Console. ReadKey ();
}
/* Running result:
===== Synchronous call of SyncInvokeTest ====
Start computing: 1 + 2
Computing complete!
Continue to do other things...
3 */
}

Synchronous calling will block the thread. If it is to call a heavy job (such as a large number of IO operations), it may pause the program for a long time, resulting in a bad user experience, at this time, asynchronous calls are necessary.
 

 

Asynchronous call

Asynchronous calls do not block threads, but plug the calls into the thread pool. The main thread or UI thread of the program can continue to execute.
The asynchronous call of the delegate is implemented through BeginInvoke and EndInvoke.
 

Public class asynchronous call
{
Static void Main ()
{
Console. WriteLine ("===== asynchronously calling AsyncInvokeTest ==== ");
AddHandler handler = new AddHandler (addition class. Add );

// IAsyncResult: Asynchronous Operation interface)
// BeginInvoke: Start of An Asynchronous Method of the delegate (delegate)
IAsyncResult result = handler. BeginInvoke (1, 2, null, null );

Console. WriteLine ("continue to do other things... ");

// Return an Asynchronous Operation
Console. WriteLine (handler. EndInvoke (result ));
Console. ReadKey ();
}
/* Running result:
===== AsyncInvokeTest ====
Continue to do other things...
Start computing: 1 + 2
Computing complete!
3 */
}

As you can see, the main thread does not wait, but runs down directly.
But the problem persists. When the main thread runs to EndInvoke, if the call is not completed (this situation is likely to occur), the thread will still be blocked to wait for the call result.
 

Asynchronous delegation can also be written as follows:

Action <object> action = (obj) => method (obj );
Action. BeginInvoke (obj, ar => action. EndInvoke (ar), null );

You can simply complete an operation in two sentences.
 

 

Asynchronous callback

When a callback function is used, the callback function is automatically called at the end of the call. This solves the situation where the thread is still blocked to wait for the call result.

Public class asynchronous callback
{
Static void Main ()
{
Console. WriteLine ("===== asynchronous callback AsyncInvokeTest ==== ");
AddHandler handler = new AddHandler (addition class. Add );

// Asynchronous Operation Interface (note that the BeginInvoke method is different !)
IAsyncResult result = handler. BeginInvoke (1, 2, new AsyncCallback (callback function), "AsycState: OK ");

Console. WriteLine ("continue to do other things... ");
Console. ReadKey ();
}

Static void callback function (IAsyncResult result)
{// Result is the return value of the "addition class. Add () method ".

// AsyncResult is an implementation class of the IAsyncResult interface. Space: System. Runtime. Remoting. Messaging
// The AsyncDelegate attribute can be forcibly converted to the actual class of the User-Defined delegate.
AddHandler handler = (AddHandler) (AsyncResult) result). AsyncDelegate;
Console. WriteLine (handler. EndInvoke (result ));
Console. WriteLine (result. AsyncState );
}
/* Running result:
===== AsyncInvokeTest ====
Start computing: 1 + 2
Continue to do other things...
Computing complete!
3
AsycState: OK
*/
}

To access AddHandler. EndInvoke, the asynchronous delegate must be forcibly converted to AddHandler. You can call MAddHandler. EndInvoke In the asynchronous callback function (AsyncCallback type) to obtain the initial AddHandler. BeginInvoke result.

 

Problem: 
 

(1) int result = handler. Invoke (1, 2 );
Why is the Invoke parameter and return value the same as the AddHandler delegate?
A:
The parameters of the Invoke method are very simple. A delegate and a parameter table (Optional). The main function of the Invoke method is to help you call the methods specified by the delegate on the UI thread.The Invoke method first checks whether the calling thread (that is, the current thread) is a UI thread. If yes, it directly executes the method pointed to by the delegate. If not, it switches to the UI thread, then execute the delegate pointing Method. Regardless of whether the current thread is a UI thread, Invoke is blocked until the execution of the method pointed to by the delegate is completed, and then the call thread is switched back (if needed) to return.
Therefore, the parameters and return values of the Invoke method should be the same as those of the delegate that calls the method.

(2) IAsyncResult result = handler. BeginInvoke (1, 2, null, null );

BeginInvoke: starts an asynchronous request and calls a thread in the thread pool for execution,
The IAsyncResult object (asynchronous core) is returned. IAsyncResult is an interface that stores the status information of asynchronous operations. It can also be used to end the current asynchronous operation.
Note: BeginInvoke and EndInvoke must be called in pairs. Even if no return value is required, EndInvoke must be called; otherwise, memory leakage may occur.

 

(3) IAsyncResult. AsyncState attributes:
Gets a user-defined object that limits or contains information about asynchronous operations. For example:

Static void AddComplete (IAsyncResult result)
{
AddHandler handler = (AddHandler) result. AsyncState;
Console. WriteLine (handler. EndInvoke (result ));
.....
}

 


 

The complete code is as follows:


Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;

Using System. Threading;
Using System. Runtime. Remoting. Messaging;

Namespace ConsoleTest
{
Public delegate int AddHandler (int a, int B );
Public class addition class
{
Public static int Add (int a, int B)
{
Console. WriteLine ("START calculation:" + a + "+" + B );
Thread. Sleep (3000); // simulate this method for three seconds
Console. WriteLine ("computing completed! ");
Return a + B;
}
}

Synchronous call of public class
{
Static void Main ()
{
Console. WriteLine ("===== synchronously call SyncInvokeTest ==== ");
AddHandler handler = new AddHandler (addition class. Add );
Int result = handler. Invoke (1, 2 );

Console. WriteLine ("continue to do other things... ");

Console. WriteLine (result );
Console. ReadKey ();
}
/* Running result:
===== Synchronous call of SyncInvokeTest ====
Start computing: 1 + 2
Computing complete!
Continue to do other things...
3 */
}

Public class asynchronous call
{
Static void Main ()
{
Console. WriteLine ("===== asynchronously calling AsyncInvokeTest ==== ");
AddHandler handler = new AddHandler (addition class. Add );

// IAsyncResult: Asynchronous Operation interface)
// BeginInvoke: Start of An Asynchronous Method of the delegate (delegate)
IAsyncResult result = handler. BeginInvoke (1, 2, null, null );

Console. WriteLine ("continue to do other things... ");

// Return an Asynchronous Operation
Console. WriteLine (handler. EndInvoke (result ));
Console. ReadKey ();
}
/* Running result:
===== AsyncInvokeTest ====
Continue to do other things...
Start computing: 1 + 2
Computing complete!
3 */
}

Public class asynchronous callback
{
Static void Main ()
{
Console. WriteLine ("===== asynchronous callback AsyncInvokeTest ==== ");
AddHandler handler = new AddHandler (addition class. Add );

// Asynchronous Operation Interface (note that the BeginInvoke method is different !)
IAsyncResult result = handler. BeginInvoke (1, 2, new AsyncCallback (callback function), "AsycState: OK ");

Console. WriteLine ("continue to do other things... ");
Console. ReadKey ();
}

Static void callback function (IAsyncResult result)
{// Result is the return value of the "addition class. Add () method ".

// AsyncResult is an implementation class of the IAsyncResult interface. Reference Space: System. Runtime. Remoting. Messaging
// The AsyncDelegate attribute can be forcibly converted to the actual class of the User-Defined delegate.
AddHandler handler = (AddHandler) (AsyncResult) result). AsyncDelegate;
Console. WriteLine (handler. EndInvoke (result ));
Console. WriteLine (result. AsyncState );
}
/* Running result:
===== AsyncInvokeTest ====
Start computing: 1 + 2
Continue to do other things...
Computing complete!
3
AsycState: OK
*/
}
}

 

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.