. NET brief introduction to component programming (asynchronous delegation)

Source: Internet
Author: User

Speaking of delegation, I think everyone has basically used it. Today this article will explain the mysteries of delegation Asynchronization.

In normal use, we seldom use Asynchronous delegation Technology to Improve code efficiency. The advantage of delegation is that it can encapsulate and transmit methods at will. It can be called in any component Customer Code, rather than passing reference to the method object, which can greatly reduce code coupling. An event is to use the advantage of delegation to transmit the message of an object .. [Wang qingpei has all rights reserved. For more information, please sign it.]

So what is asynchronous delegation? To put it simply, we call a method asynchronously. However, if we call the method directly using a working thread (implemented by the main entry), it is definitely not asynchronous. To make asynchronous calls, subthreads must be used to complete the call, so that the main thread can handle some key things, such as user interface response and button event processing. This principle does not allow users to wait.

Next we will learn about the technology of asynchronous delegation.

Let's take a look at a simple piece of code 1:

 
 
  1. Using System;
  2. Using System. Collections. Generic;
  3. Using System. Text;
  4.  
  5. Namespace ConsoleApplication1
  6. {
  7. /// <Summary>
  8. /// Delegate used for calculation
  9. /// </Summary>
  10. /// <Param name = "I"> parameter 1 </param>
  11. /// <Param name = "y"> parameter 2 </param>
  12. /// <Returns> calculation result </returns>
  13. Public delegate int BinaryOperaton (int I, int y );
  14. /// <Summary>
  15. /// Computing class
  16. /// </Summary>
  17. Public class Calculator
  18. {
  19. /// <Summary>
  20. /// Add two numbers
  21. /// </Summary>
  22. /// <Param name = "argument1"> </param>
  23. /// <Param name = "argument2"> </param>
  24. /// <Returns> </returns>
  25. Public int Add (int argument1, int argument2)
  26. {
  27. Return argument1 + argument2;
  28. }
  29. /// <Summary>
  30. /// Subtract two numbers
  31. /// </Summary>
  32. /// <Param name = "argument1"> </param>
  33. /// <Param name = "argument2"> </param>
  34. /// <Returns> </returns>
  35. Public int Subtract (int argument1, int argument2)
  36. {
  37. Return argument1-argument2;
  38. }
  39. }
  40. }

This is a common code that contains a delegate definition and a computing class. Let's use the defined delegate to explain the asynchronous call of the delegate .. [Wang qingpei has all rights reserved. For more information, please sign it.]

When we use the delegate, we usually use the following method 2:

 
 
  1. // Synchronous call
  2. Calculator calcularor = new Calculator ();
  3. BinaryOperaton operation = calcularor. Add;
  4. Console. WriteLine (operation (10, 20 ));
  5. Console. ReadLine ();

We Add the Calculator instance method Add to the delegate list, and then use synchronous call, that is, directly use the delegate instance to call. If the processing time of the Add method is long, the main working thread will be blocked until the end of the Add method.

So how to make the delegate asynchronous call involves the true principle behind the scenes of the delegate.

In fact, when we define a Delegate, the compiler will compile it into an object inherited from the "MulticastDelegate" class. The "MulticastDelegate" object is also inherited from the Delegate abstract base class. Therefore, the delegate we set is not a package of simple methods. It contains complicated implementation logic and supports asynchronous calls. Of course, asynchronous calls are implemented by the Base class, it applies for help. NET background thread pool threads to call methods, so that the worker thread can continue to process important things, rather than doing so.

Let's take a look at the delegated asynchronous call code 3:

 
 
  1. Calculator calcularor = new Calculator ();
  2. BinaryOperaton operation = calcularor. Add;
  3. IAsyncResult result = operation. BeginInvoke (10, 20, null, null); // the asynchronous delegate can only be referenced by one method
  4. Console. ReadLine ();

The BeginInvoke of the delegate is used for asynchronous calling. Where is the definition of this method? It is automatically generated by the system in the background. Different delegate signatures use different BeginInvoke methods, therefore, dynamic compilation is required. [MSDN: The Runtime Library in the public language automatically defines the BeginInvoke and EndInvoke methods for the delegate using the appropriate signature.]

In code 3, The IAsyncResult interface appears. This is an asynchronous Status interface. What does this mean. IAsyncResult holds a reference to the status during asynchronous operations. Of course, the state in asynchronous delegation is actually mastered by the AsyncResult object. What we actually get is the reference of the AsyncResult object.

Figure 1:

650) this. width = 650; "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1S60QS5-0.png "border =" 0 "/>

This figure shows why IAsyncResult knows what the thread is doing. Let's continue.

Because the IAsyncResult interface stores the execution status of asynchronous threads, we can use the IAsyncResult interface to determine whether the thread has been completed.

 
 
  1. // AsyncDelegate in AsyncResult
  2. Calculator calcularor = new Calculator ();
  3. BinaryOperaton operation = calcularor. Add;
  4. // The forced type returned by the IAsyncResult interface in delegate use is the AsyncResult delegate asynchronous State object
  5. AsyncResult result = (AsyncResult) operation. BeginInvoke (10, 20, null, null );
  6. If (! Result. EndInvokeCalled)
  7. {
  8. // Use AsyncResult to obtain the delegate instance that originally called BeginInvoke.
  9. Int count = (result. AsyncDelegate as BinaryOperaton). EndInvoke (result );
  10. Console. WriteLine (count );
  11. }
  12. Console. ReadLine ();

Without our knowledge, we can use the IAsyncResult interface to perform unified asynchronous operations.. NET platform can see asynchronous calling methods everywhere. For example, some Stream objects in the IO namespace provide asynchronous Stream reading methods. You must implement the IAsyncResult interface on your own to implement the messages passed in asynchronous mode.

With Asynchronous calls, you must obtain the execution result when appropriate. There are several methods to obtain the end result of an asynchronous operation, including loop wait, wait handle, and asynchronous callback. Let's take a look at these methods.

Loop wait

 
 
  1. // Asynchronous call. Loop wait
  2. Calculator calcularor = new Calculator ();
  3. BinaryOperaton operation = calcularor. Add;
  4. IAsyncResult result = operation. BeginInvoke (10, 20, null, null); // the asynchronous delegate can only be referenced by one method
  5. While (! Result. IsCompleted) // use IsCompleted to determine whether the asynchronous operation has ended. true indicates that the asynchronous operation has ended, and false indicates that the asynchronous operation has not ended.
  6. {
  7. Int count = operation. EndInvoke (result );
  8. Console. WriteLine (count );
  9. }
  10. Console. ReadLine ();

Waiting handle WaitHandle

 
 
  1. // Wait until the polling is completed.
  2. Calculator calcularor = new Calculator ();
  3. BinaryOperaton operation = calcularor. Add;
  4. IAsyncResult result = (AsyncResult) operation. BeginInvoke (10, 20, null, null );
  5. // Block the current thread until the method ends. Wait for 4 seconds. Returns true if the current instance receives a signal; otherwise, false.
  6. While (true)
  7. {
  8. If (result. AsyncWaitHandle. WaitOne (4000 ))
  9. Break;
  10. }
  11. Int count = operation. EndInvoke (result );
  12. Console. WriteLine (count );
  13. Console. ReadLine ();

We can determine the resource by obtaining the waiting handle. The waiting handle is an unmanaged encapsulation of the Windows system, indicating the logical object of the critical resource. The operating system has full access to it. With. NET, you can easily use this type of logical object to abstract the resources we want to synchronize and use. This achieves mutual exclusion.

The Code uses WaitHandle. the WaitOne method waits for four seconds. If a signal is not received within the specified time, the method returns false, and the waiting continues. The asynchronous operation ends only when true is returned.

Asynchronous callback

 
 
  1. // Asynchronous callback
  2. Calculator calcularor = new Calculator ();
  3. BinaryOperaton operation = calcularor. Add;
  4. Operation. BeginInvoke (10, 20, OnCompletion, true); // asynchronous callback can pass in appropriate parameters
  5. Console. ReadLine ();
 
 
  1. static void OnCompletion(IAsyncResult asyresult)  
  2.        {  
  3.            AsyncResult comresult = asyresult as AsyncResult;  
  4.            int count = (comresult.AsyncDelegate as BinaryOperaton).EndInvoke(comresult);  
  5.            if ((bool)comresult.AsyncState == true)  
  6.                Console.WriteLine("true");  
  7.            Console.WriteLine(count);  
  8.  
  9.        } 

Asynchronous callback is the best method to use. It is simple and convenient and can be processed after different client codes are completed, the AsyncResult Instance Object of the IAsyncResult interface obtains the operation result of the asynchronous instance object. In fact, another important thing is the last parameter in the BeginInvoke method. In fact, this parameter is used to pass the callback method parameters. Because the signature of the callback method cannot be changed, only the IAsyncResult interface can be used as the parameter. Therefore, we can only pass the last parameter of the BeginInvoke method, and then obtain it through the AsyncState attribute of the AsyncResult object.

At the end of this article, let's take a look at the use of asynchronous events.

Because the event is based on the delegate, we can use the event to asynchronously call the subscriber's method, but we cannot directly perform BeginInvoke as usual, only when there is only one delegate method in the delegate list can BeginInvoke be used directly. If there is one additional delegate method, it must be called cyclically.

 
 
  1. // Asynchronous event
  2. Delegate [] delegatelist = numberchangle. GetInvocationList ();
  3. Foreach (Delegate dele in delegatelist) // asynchronous events must be called separately
  4. {
  5. (Dele as BinaryOperaton). BeginInvoke (10, 20, null, null );
  6. }

Through the Delegate base class, we can obtain the Delegate instance in the Delegate list, and then call their respective methods cyclically .. [Wang qingpei has all rights reserved. For more information, please sign it.]

 

This article is from the pattern driven the world blog, please be sure to keep this source http://wangqingpei557.blog.51cto.com/1009349/647862

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.