C # asynchronous call

Source: Internet
Author: User

The company needs to call an external webservice for work. At the same time, it needs to save the outgoing data. As a result, we plan to perform operations step by step as we used, I have never considered the user experience. With my colleagues' guidance, I am aware of the benefits of using asynchronous calls. I just want to save some information I have found so that I can avoid mistakes!
We need to clarify why asynchronous callback is required? As we all know,The normal method is running in a single thread.If there are large operations (such as reading large files, operating databases in large batches, and network transmission) in the middle ),Will cause method Blocking, Which is displayed on the interface,Program card or dead, interface elements do not moveNo response. The asynchronous method solves these problems well,Asynchronous execution of a method, the program immediately opens up a new thread to run your method, the main thread including the interface will not die. Now we are talking about how to end this asynchronous new thread.
First, the new asynchronous thread must be recycled,Not recycling is a shameful waste of resources, and. NET is also not allowed, so you do not want to exploit the loopholes, as the saying goes, please be easy to God, this is the truth. You can easily think of two types of recycling:Active recoveryAndPassive recovery(Of course, this is my own understanding. That's not what Microsoft says ),Active collection means that you monitor the thread and wait. When the Asynchronous Method is complete, the asynchronous thread is recycled and the focus is returned to the main thread.In fact, it is the case in the previous article "C # asynchronous preliminary,BeginInvoke is followed by EndInvoke. If the asynchronous thread does not complete the operation during EndInvoke, the entire program, including the main thread, is blocked again, the interface is "dead.To solve this problem, useOne of the most important methods for "passive recovery" is "Asynchronous callback ".
Core:
A,Call the callback function (CallBackMethod in this example) automatically after the asynchronous operation ends.
B. Do not manually wait for the asynchronous end in the main thread. In the above two examples, EndInvoke is called in the main thread. This method isCall EndInvoke In the callback function.
The general process of asynchronous callback is as follows:First, start Asynchronization, add the method executed at the end of Asynchronization to the startup parameter, and then the asynchronous thread will not worry about it. Finally, when the asynchronous thread completes its work, the method in the startup parameter is automatically executed.This is really easy, but it is complicated to write the code.
The code for souzang is as follows:
// First, prepare the Asynchronous Method (asynchronous, preferably not multithreading)
Private string MethodName (int Num, out int Num2)
{
Num2 = Num;
Return "HelloWorld ";
}

// Program endpoint
// The method (callback method) to be executed when asynchronous completion is completed. This method can only have one IAsyncResult parameter, but this parameter is almost omnipotent and can be passed to the object.
Private void CallBackMethod (IAsyncResult ar)
{
// Obtain the delegate object from the asynchronous ar. AsyncState.
DelegateName dn = (DelegateName) ar. AsyncState;
// Output parameters
Int I;

// Be sure to use EndInvoke. Otherwise, your end will be miserable.
String r = dn. EndInvoke (out I, ar );
MessageBox. Show ("Asynchronous completion! The value of I is "I. ToString ()", and the value of r is "r );
}

// Define the delegate with the same signature as the method
Private delegate string DelegateName (int Num, out int Num2 );

// Program entry
Private void Run ()
{
// Instantiate the delegate and assign a value first
DelegateName dn = new DelegateName (MethodName );
// Output parameters
Int I;
// Instantiate the callback Method
//Think of AsyncCallback as Delegate. In fact, AsyncCallback is a Special Delegate, just like Event.
AsyncCallback acb = new AsyncCallback (CallBackMethod );
// Asynchronous Start
//If the value of acb is null, no callback method is available.
// LastThe parameter dn can be replaced with any object, which can be obtained by the callback method from the parameter.And can be written as null. The parameter dn is equivalent to the thread ID,If multiple asynchronous threads exist, they can all be null, but they cannot be the same. They cannot be the same object. Otherwise, an exception occurs.
IAsyncResult iar = dn. BeginInvoke (1, out I, acb, dn );
// Do other things
//............
}

// The final result should be: I = 1, r = "HelloWorld"

In addition, if you can, you can choose not to modify too much when defining the delegate:

/// <Summary>
/// Define the delegate
/// </Summary>
/// <Returns> </returns>
Public delegate bool Asyncdelegate ();

/// <Summary>
/// Callback method must have the same signature as
/// AsyncCallback delegate
/// </Summary>
/// <Param name = "ar"> </param>
Private void CallbackMethod (IAsyncResult ar)
{
// Retrieve the delegate.
Asyncdelegate dlgt = (Asyncdelegate) ar. AsyncState;

// Call EndInvoke to retrieve the results.
Dlgt. EndInvoke (ar );
}

Call other methods:
// Asynchronous execution
// Specify the delegate Method
Asyncdelegate isgt = new Asyncdelegate (icpInfo. Insert );
IAsyncResult ar = isgt. BeginInvoke (new AsyncCallback (CallbackMethod), isgt );

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.