Review asynchronous Delegation

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, 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 on the interface, Program Card or die, the interface element does not move, no response. 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. 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 need to 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. This is actually the first article. Article In C # asynchronous preliminary, endinvoke is followed by begininvoke. If the asynchronous thread does not complete the operation at endinvoke, the entire program, including the main thread, it is blocked again, and the interface will be "dead. To solve this problem, we should adopt the "passive reclaim" method. An important method is "Asynchronous callback ". There are two core components: A. Use a callback function (callbackmethod in this example) to automatically call this callback function after The Asynchronization 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 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, Code Writing is complicated. 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 during asynchronous completion. This method can only have one iasyncresult parameter, but this parameter is almost omnipotent and can pass 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 () "  , 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 values first Delegatename DN = New  Delegatename (methodname );  //  Output Parameters                  Int  I;  //  Instantiation 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.  //  The last parameter dn can be replaced with any object, which can be obtained by the callback method 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, 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 Delegation  ///   </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 );

 

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.