. NET component programming asynchronous invocation

Source: Internet
Author: User
Tags assert object definition bool execution net net thread thread

When it comes to asynchronous invocation, the first thought in mind is BeginInvoke (), and in some common objects we often see Invoke () and BeginInvoke (), and it is reasonable to make your component callable by the client or asynchronously. This is also one of the component asynchronous mechanisms (aside from the fact that most of the knowledge is hidden in the objects we often see or in the code, but not carefully) in. NET, the first idea is to use a delegate for asynchronous invocation, and the definition of the delegate is Delegates and events in the article has probably said, the article is only a general description of the delegate, and did not use the delegate to explain or examples of some examples. In this article we will make a basic Bandi of the delegate, the main direction is asynchronous invocation.

A commission of the old refrain

public class Operation
{public
int addition (int num1, int num2)
{
return        NUM1 + num2;
public
int subtraction (int num1, int num2)
{return
num1-num2;
}
}

There is no need to use the Operation object directly to add and subtract operations, you can use the delegate:

public delegate int operationdelegate (int num1, int num2);

Operation Operation = new Operation ();
Operationdelegate additiondelegate = operation. addition;

int result;
result = Additiondelegate.invoke (3, 4);
Debug.Assert (Result = = 7);

When invoked with a delegate, the current thread is blocked and the control is returned to the current thread only when the delegate has finished executing.
However, a delegate can be used to invoke the target method asynchronously, and the delegate is only a specific type, and the compiler compiles the various delegates we define into
The corresponding class, like the Operationdelegate delegate, is actually compiled into such

public sealed class Operationdelegate:multicastdelegate     {      & nbsp Public Operationdelegate (Object target, int methodptr) {}         public virtual Invoke (int num1,int num2)         {             ...        }          Public virtual IAsyncResult BeginInvoke (int num1,int num2,asynccallback callback,object asyncstate)          {            ...         }         public virtual int EndInvoke ( IAsyncResult result)         {             ...        }   &NBsp }

Here is a review of the definition of the delegate.

Two-asynchronous calling programming model

Figure 1

In the above diagram we see that there are these few modules,. NET thread pool, the asynchronous call request queue, and the main thread of an application.
If now from Task 1 to Task 2, Task 3, to Task 3, task 3 requests. NET performs asynchronous operations, as shown in Figure 2

Figure 2

This time "Task 3" has been sent into the "asynchronous request queue" and the main thread is blocked, and then look at the execution of Figure 3:

Figure 3

The thread pool will discover the tasks in the asynchronous request queue in a timely manner, and the thread pool assigns a thread to the task's main thread to perform the requested tasks, depending on the task's information. When the asynchronous task executes, this time the main thread is withdrawn from the block, into the execution state, in the figure above, to start Task 4.

Here is to say, the asynchronous call seems to be executed in parallel, actually at the beginning of the sequence, but this time in the actual situation is negligible, it can be thought that the parallel implementation of the bar.

Three BeginInvoke (), 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}

Accept the input parameters of the original signature defined by the Operationdelegate delegate, and two additional parameters, AsyncCallback is a system-defined delegate that is used by the callback when the call completes asynchronously, not explained here, and then there is a parameter is a state object. It can also be considered a container object and will be described in a later section.

1 Operation Operation = new Operation (); 2 operationdelegate additiondelegate = operation. addition; 3 Additiondelegate.begininvoke (3, 4, NULL, NULL);

3.2 IAsyncResult Interface

As you can see above, the BeginInvoke function returns a value of IAsyncResult type, so let's look at the definition of IAsyncResult:

Public interface IAsyncResult
{
object asyncstate {get;}
WaitHandle asyncwaithandle {get;}
BOOL completedsynchronously {get;}
BOOL iscompleted {get;}
}

Detailed usage of IAsyncResult will be explained later

When you see the Invoke function in the first section, you can get the return value directly, how does this BeginInvoke function perform a return

IAsyncResult type, where is the return value? You can get the return value by handing the EndInvoke function to the IAsyncResult obtained from the BeginInvoke function.

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);

Here's a few things to say.

First, when the EndInvoke function is invoked, the current thread is blocked and waits for the BeginInvoke function to finish executing.

Second, although a delegate can manage multiple target methods, in an asynchronous invocation, the internal management list can only have one target method, or an exception is reported, in the delegate that executes the asynchronous call.

Third. EndInvoke () can only be invoked once per asynchronous invocation operation.

Fourth. An instance of the IAsyncResult type returned by BeginInvoke () can only be passed into the EndInvoke () of the BeginInvoke () delegate to which it is invoked, otherwise an exception is reported.

3.3 asyncresult

If a client uses BeginInvoke () in a code snippet or function, and calls EndInvoke () in another or other function, does the client have to save the IAsyncResult object, or if a client initiates an asynchronous call, And by another client to invoke EndInvoke (), not only to save the IAsyncResult object, but also to save the delegate object, and you have to transfer the past. OK. NET is so witty that there are System.Runtime.Remoting.Messaging.AsyncResult types of existence.

public class Asyncresult:iasyncresult, IMessageSink
{

#region IAsyncResult Members

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 Members
}

Look at the above there is a asyncdelegate attribute, will not feel very beautiful, yes, it is the original initiator of the reference, see how to use AsyncDelegate to use EndInvoke ():

public class Operationtest
{

public void Test ()
{
Operation Operation = new Operation ();
Operationdelegate additiondelegate = operation. addition;
int result;
result = GetResult (Additiondelegate.begininvoke (3, 4, NULL, NULL));
}

private int GetResult (IAsyncResult asyncresult)
{
AsyncResult asyncresult = (asyncresult) asyncresult;
Operationdelegate operationdelegate = asyncresult.asyncdelegate as

Operationdelegate;
if (operationdelegate!= null)
{
Debug.Assert (asyncresult.endinvokecalled = = False);//endinvoke () has been invoked
Return operationdelegate. EndInvoke (asyncresult);
}
return-1;
}
}

3.4 Round-robin or waiting

See here, good thinking friend will find that there is still a big problem, is the launch of the asynchronous call client, how to know that their asynchronous function is finished? or want to wait for a while, do some other processing, and then continue to wait, how to achieve it?

The IAsyncResult interface returned from BeginInvoke () has a asyncwaithandle attribute, what is it? Just understand it as a message receiver.

Operation Operation = new Operation ();
Operationdelegate additiondelegate = operation. addition;
IAsyncResult asyncresult = Additiondelegate.begininvoke (2, 3, NULL, NULL);
AsyncResult.AsyncWaitHandle.WaitOne ();//If the task is complete, it will not block or block the current thread
int result;
result = Additiondelegate.endinvoke (asyncresult);
Debug.Assert (Result = = 5);

The code is almost the same as 3.2, and the difference is that this code guarantees that the caller of the EndInvoke () will not be blocked.

Look at the wait, if not complete the other tasks, back to wait for how to achieve.

Operation Operation = new Operation ();
Operationdelegate additiondelegate = operation. addition;
IAsyncResult asyncresult = Additiondelegate.begininvoke (2, 3, NULL, NULL);
while (asyncresult.iscompleted = = false)//determines whether the asynchronous task completes
{
AsyncResult.AsyncWaitHandle.WaitOne (10,false);//If the task completes, it will not block or block the current thread for 10 milliseconds
Here do some other things
}
int result;
result = Additiondelegate.endinvoke (asyncresult);
Debug.Assert (Result = = 5);

3.5 Using Callback functions

Now we're going to say the third parameter of BeginInvoke (), public delegate void AsyncCallback (IAsyncResult ar);

The third parameter is a system-supplied delegate type, and the delegate signature is also seen. The advantage of using a callback function is that there is no need to handle the wait operation, because when the asynchronous task completes, it calls you to the target method associated with the AsyncCallback delegate in BeginInvoke ().

public class Operationtest
{

public void Test ()
{
Operation Operation = new Operation ();
Operationdelegate additiondelegate = operation. addition;

Additiondelegate.begininvoke (2, 3, new AsyncCallback (OnCallback), null);
}

private void OnCallback (IAsyncResult asyncresult)
{
AsyncResult asyncresult = (asyncresult) asyncresult;
Operationdelegate operationdelegate = asyncresult.asyncdelegate as

Operationdelegate;
if (operationdelegate!= null)
{
Debug.Assert (asyncresult.endinvokecalled = = false);
int result=operationdelegate. EndInvoke (asyncresult);
Console.WriteLine ("Operation returned" + result. ToString ());
}
}
}

What you need to say here is that when the asynchronous task completes, the callback function executed is still in the child thread, not the callback function in the main thread.

Digression: The most common is to initiate an asynchronous call in the form in WinForm development, and then the callback function to manipulate the controls in the form or

Value, this is the reason, because they are not in a thread nor in a context, based on. NET security Policy This operation is not allowed.



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.