Program Design of. Net component-asynchronous calling

Source: Internet
Author: User
Tags net thread

Program Design of. Net component-asynchronous calling

When it comes to asynchronous calls, the first thought in my mind is BeginInvoke (). In some common objects, we often see Invoke () and BeginInvoke (), this design is reasonable if you want your components to be called by the client or asynchronously, this is also one of the components asynchronous mechanism (speaking out of question-in fact, most of the knowledge is hidden in the objects or code we often see, but it is not carefully discovered. NET will first come up with the idea of using a delegate for asynchronous calls. The definition of the delegate has been mentioned in the delegate and event article. In this article, I just gave a rough explanation of the delegate, the use of delegation is not described or examples are given. In this article, we will reveal the basis of the Delegate, with the main direction being asynchronous calls.

A commissioned veteran

 1     public class Operation 2     { 3         public int Addition(int num1, int num2) 4         { 5             return num1 + num2; 6         } 7         public int Subtraction(int num1, int num2) 8         { 9             return num1 - num2;10         }11     }

There is no need to directly use the Operation object for addition and subtraction operations. You can use the delegate:

1 public delegate int OperationDelegate(int num1, int num2);2 3 Operation operation = new Operation();4 OperationDelegate Additiondelegate = operation.Addition;5 6 int result;7 result = Additiondelegate.Invoke(3, 4);8 Debug.Assert(result == 7);

When the delegate is used for calling, the current thread is blocked. The control is returned to the current thread only when the delegate execution is complete.
However, the delegate can be used to call the target method asynchronously. The delegate is only a specific type, and the compiler will compile all kinds of delegates we define
The corresponding class, like the OperationDelegate delegate, is actually compiled into this

 1     public sealed class OperationDelegate : MulticastDelegate 2     { 3         public OperationDelegate(Object target, int methodPtr) { } 4         public virtual Invoke(int num1,int num2) 5         { 6             …… 7         } 8  9         public virtual IAsyncResult BeginInvoke(int num1,int num2,AsyncCallback 10 11 callback,object asyncState)12         {13             ……14         }15 16         public virtual int EndInvoke(IAsyncResult result)17         {18             ……19         }20     }

Here is a review of the definition of delegation.

Binary asynchronous call Programming Model

Figure 1

We have seen these modules, the. NET thread pool, the asynchronous call Request queue, and the main thread of an application.
If Task 2, Task 3, and task 3 are executed from Task 1 to task 2 and Task 3, Task 3 requests. NET to execute asynchronous operations

Figure 2

At this time, [Task 3] has been sent to the [asynchronous request queue], and the main thread is blocked. Then, we can see the execution process in Figure 3:

Figure 3

The thread pool will promptly discover tasks in the asynchronous request queue. Based on the task information, the thread pool will allocate a thread to the main thread where the task is located to execute the requested task. When an asynchronous task is executed, the main thread will undo it from the blocking and enter the execution status, which is to start Task 4.

The asynchronous call seems to be executed in parallel, but it is still sequential at the beginning. However, the actual time is negligible, it can be considered as parallel execution.

BeginInvoke () and EndInvoke ()

3.1 BeginInvoke ()

The BeginInvoke () function is defined as follows:

1 public virtual IAsyncResult BeginInvoke(int num1,int num2,AsyncCallback callback,object asyncState)2 {3    ……4 }

The input parameter of the original signature defined by the OperationDelegate delegate is accepted. There are two additional parameters. AsyncCallback is the system-defined delegate used for callback when asynchronous calls are completed. This will not be explained here, another is that a parameter is a State object, which can also be considered a container object, which will also be discussed in later chapters.

1 Operation operation = new Operation();2 OperationDelegate Additiondelegate = operation.Addition;3 Additiondelegate.BeginInvoke(3, 4, null, null);

3.2 IAsyncResult Interface

As shown above, the BeginInvoke function returns an IAsyncResult type value, so let's take a look at the definition of IAsyncResult:

1     public interface IAsyncResult2     {3         object AsyncState { get; }4         WaitHandle AsyncWaitHandle { get; }5         bool CompletedSynchronously { get; }6         bool IsCompleted { get; }7     }

Detailed usage of IAsyncResult will be explained later

After the Invoke function is executed in section 1, the return value can be obtained directly. How can this BeginInvoke function be executed and returned?

IAsyncResult type. Where is the returned value? The IAsyncResult obtained from the BeginInvoke function can be handed over to the EndInvoke function to obtain the return value.

1 Operation operation = new Operation();2 OperationDelegate Additiondelegate = operation.Addition;3 4 IAsyncResult asyncResult = Additiondelegate.BeginInvoke(3, 4, null, null);5 int result = Additiondelegate.EndInvoke(asyncResult);6 Debug.Assert(result == 7);

What are the points to be made here?

1. When the EndInvoke function is called, the current thread is blocked and it is waiting for the BeginInvoke function to be executed.

2. Although the delegate can manage multiple target methods, the internal management list can only have one target method for the delegate for asynchronous calls in asynchronous calls. Otherwise, an exception is reported.

Third, EndInvoke () can be called only once each asynchronous call operation.

Fourth, the IAsyncResult type instance returned by BeginInvoke () can only be passed into the EndInvoke () of the BeginInvoke () delegate it calls. Otherwise, an exception is reported.

 

3.3 AsyncResult

If a client uses BeginInvoke () in a code segment or function and calls EndInvoke () in another section or other functions, does the client need to save the IAsyncResult object, alternatively, a client initiates an asynchronous call and another client calls EndInvoke (). This not only saves the IAsyncResult object, but also saves the delegate object, and you have to transfer it to the client. Fortunately,. NET is so witty that there are systems. Runtime. Remoting. Messaging. AsyncResult types.

Public class AsyncResult: IAsyncResult, IMessageSink {# region IAsyncResult member public object AsyncState {get {throw new NotImplementedException () ;}} public System. threading. waitHandle AsyncWaitHandle {get {throw new NotImplementedException () ;}} public bool CompletedSynchronously {get {throw new NotImplementedException ();}} public bool IsCompleted {get {throw new NotImplementedException () ;}# endregion public bool EndInvokeCalled {get; set;} public virtual object AsyncDelegate {get;} // IMessageSink member}

Looking at the AsyncDelegate attribute on the top, will it look pretty good? It is a reference to the original initiate delegate. Let's see how to use AsyncDelegate to use EndInvoke ():

1 public class OperationTest 2 {3 4 public void Test () 5 {6 Operation operation = new Operation (); 7 OperationDelegate Additiondelegate = operation. addition; 8 int Result; 9 Result = GetResult (Additiondelegate. beginInvoke (3, 4, null, null); 10} 11 12 private int GetResult (Response Results) 13 {14 asyncresult AsyncResult = (asyncResult) AsyncResult; 15 OperationDelegate operationdelegate = YncResult. AsyncDelegate as 16 17 OperationDelegate; 18 if (operationdelegate! = Null) 19 {20 Debug. assert (asyncResult. endInvokeCalled = false); // whether EndInvoke () has been called 21 return operationdelegate. endInvoke (asyncResult); 22} 23 return-1; 24} 25}

3.4 Round Robin or waiting

As you can see, a thoughtful friend will find that there is still a big problem, that is, the client that initiates an asynchronous call. How can I know if my asynchronous function has been executed? Or you want to wait for a while, do some other processing, and then continue to wait. How can this problem be achieved?

The IAsyncResult interface returned from BeginInvoke () has an AsyncWaitHandle attribute. What does it do? Let's take it as a message receiver.

1 Operation operation = new Operation (); 2 OperationDelegate Additiondelegate = operation. addition; 3 IAsyncResult asyncResult = Additiondelegate. beginInvoke (2, 3, null, null); 4 asyncResult. asyncWaitHandle. waitOne (); // if the task is completed, it will not be blocked; otherwise, it will block the current thread 5 int Result; 6 Result = Additiondelegate. endInvoke (asyncResult); 7 Debug. assert (Result = 5 );

The code is almost the same as that of 3.2. The difference is that this Code ensures that callers of EndInvoke () are not blocked.

Let's take a look at the waiting process. If other tasks are not completed, how can we wait for them to come back.

1 Operation operation = new Operation (); 2 OperationDelegate Additiondelegate = operation. addition; 3 IAsyncResult asyncResult = Additiondelegate. beginInvoke (2, 3, null, null); 4 while (asyncResult. isCompleted = false) // determines whether the asynchronous task is completed. 5 {6 asyncResult. asyncWaitHandle. waitOne (10, false); // if the task is completed, it will not be blocked; otherwise, the current thread will be blocked for 10 milliseconds 7 // here some other operations 8} 9 int Result; 10 Result = Additiondelegate. endInvoke (asyncResult); 11 Debug. assert (Result = 5 );

3.5 Use callback Functions

Now let's talk about the third parameter of BeginInvoke (), public delegate void AsyncCallback (IAsyncResult ar );

The third parameter is a delegate type provided by the system. The delegate signature is also displayed. The advantage of using the callback function is that you do not need to wait for the operation, because when the asynchronous task is completed, it will call the target method associated with the AsyncCallback delegate in BeginInvoke.

 1     public class OperationTest 2     { 3  4         public void Test() 5         { 6             Operation operation = new Operation(); 7             OperationDelegate Additiondelegate = operation.Addition; 8  9             Additiondelegate.BeginInvoke(2, 3, new AsyncCallback(OnCallBack), null);10         }11 12         private void OnCallBack(IAsyncResult asyncresult)13         {14             AsyncResult asyncResult = (AsyncResult)asyncresult;15             OperationDelegate operationdelegate = asyncResult.AsyncDelegate as 16 17 OperationDelegate;18             if (operationdelegate != null)19             {20                 Debug.Assert(asyncResult.EndInvokeCalled == false);21                 int result=operationdelegate.EndInvoke(asyncResult);22                 Console.WriteLine("Operation returned" + result.ToString());23             }24         }25     }

It should be said that when the asynchronous task is completed, the callback function executed is still in the subthread, not in the main thread.

Question: In Winform development, asynchronous calling is initiated in Form, and then a callback function is used to operate controls in Form or

This is the reason, because they are not in the same thread or context, they are not allowed Based on. NET security policies.

END

 

 

Author: Jin Yuan

Source: http://www.cnblogs.com/jin-yuan/

The copyright of this article is shared by the author and the blog Park. You are welcome to reprint this article. However, you must keep this statement without the author's consent and go to the Article Page.

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.