C # asynchronous call method,

Source: Internet
Author: User

C # asynchronous call method,

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, normal methods run in a single thread. Large operations (such as reading large files, operating databases in large batches, and network transmission) in the middle will lead to method blocking, as shown in the interface, the program is stuck or dead, and the interface elements do not change and do not respond. The asynchronous method solves these problems. When a method is executed asynchronously, 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. C # advantages and methods of asynchronous calls

First, the asynchronous new thread must be recycled. It is a shameful waste of resources ,. NET is also not allowed, so you do not want to explore the loopholes, as the saying goes, please be easy to god, it is this truth. Next, you can easily think of two types of recovery: active recovery and passive recovery (of course, this is my understanding, but Microsoft does not say so). Active recovery is, you can monitor the thread and wait. When the Asynchronous Method is complete, the asynchronous thread will be recycled and the focus will be returned to the main thread, which is actually 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, we should adopt the "passive reclaim" method. An important method is "Asynchronous callback ".
Core:
A. Use the callback function (CallBackMethod in this example). After the Asynchronous Method ends, the callback function is automatically called.
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 calls EndInvoke In the callback function.
The general process of asynchronous callback is as follows: first, start Asynchronization. Then, the startup parameter is added with the method executed at the end of Asynchronization. Then, this asynchronous thread will be ignored, finally, when the asynchronous thread completes the work, it will automatically execute the method in the startup parameter, which is indeed very worry-free, but it is very 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";}/* He asked hovertree.com * // specifies the method (callback method) to be executed when the program end point is completed asynchronously. This method can only have one IAsyncResult parameter, however, this parameter is almost omnipotent and can pass objectprivate void CallBackMethod (IAsyncResult ar) {// from the asynchronous state ar. in AsyncState, obtain the delegate object DelegateName dn = (DelegateName) ar. asyncState; // output parameter int I; // be sure to use EndInvoke; otherwise, your end is miserable. string r = dn. endInvoke (out I, ar); M EssageBox. Show ("Asynchronous completion! The value of I is "I. toString () ", the value of r is" r);} // defines the delegate private delegate string DelegateName (int Num, out int Num2) with the same signature as the method ); // program entry private void Run () {// instantiate the delegate and assign DelegateName dn = new DelegateName (MethodName); // output parameter int I; // instantiate the callback method // you will understand AsyncCallback as Delegate. In fact, AsyncCallback is a Special Delegate, just like AsyncCallback acb = new AsyncCallback (CallBackMethod ); // Asynchronous Start // If the parameter acb is changed to null, it indicates that no callback method is available. // The last parameter dn can be changed to any object. This object can The callback method can be obtained from the parameter and 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, IAsyncResult iar = dn is abnormal. beginInvoke (1, out I, acb, dn); // do something else //............} // 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 the // 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);}/* He asked hovertree.com */

Call other methods:

// Asynchronous execution // specify the delegate method/* Ask hovertree.com */Asyncdelegate isgt = new Asyncdelegate (icpInfo. insert); IAsyncResult ar = isgt. beginInvoke (new AsyncCallback (CallbackMethod), isgt );

Recommended: http://www.cnblogs.com/roucheng/p/3521864.html

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.