Asynchronous and synchronous delegation, the return value of the delegation is asynchronous, just like the East stream of spring water (asynchronous delegation you know)

Source: Internet
Author: User
Asynchronous delegation is like a stream of spring water flowing to the East (asynchronous delegation you know)

Books are books, you are you, and text copying is a book. You must understand it yourself, even if you have a wrong understanding. Next, let's talk about asynchronous delegation. The individual is not deeply involved in. net and has little experience. If not, I hope you can point it out.
For the thread, I don't want to talk about it. I can search for the "thread and thread" in the blog garden, which is quite detailed. This blog post is intended for: friends who know some threads but are vague about asynchronous delegation.
In fact, this asynchronous delegate should be discussed together with the Thread. Why do we like this asynchronous delegate for three reasons:
. The execution of the main thread is not affected.
. Reasonably use ThreadPool thread pool threads
Asynchronous delegation is essentially a worker thread that calls the thread pool. It is managed by the thread pool in a unified manner to avoid the headache of creating and canceling threads.

1. Traditional synchronous delegation (the method for simulating delegation takes a long time to execute)
The method used to simulate the delegate is executed for a long time: Thread. Sleep (TimeSpan. FromSeconds (3 ));

View Code

// Declare the delegate
Public delegate void DeleMethod (string name );
Class Program
{
Static void Main (string [] args)
{
DeleMethod delemethod = Speaking;
Delemethod ("Mr. w ");
Console. WriteLine ("I want to execute the method ....");

}

// Method to be called by Delegate
Static void Speaking (string name)
{
Console. WriteLine ("My name is {0}", name );
// Uses sleep for 3 seconds, and the method for simulating delegated execution is long.
Thread. Sleep (TimeSpan. FromSeconds (3 ));
Console. WriteLine ("the delegate method has been executed! ");
}
Copy code

Analysis:
. According to F11, everyone can analyze it by themselves. Main () is the start of all programs. The program calls the Speaking () method to sleep for 3 seconds, this affects the method execution time below the main thread.
From start to end, the program has only one thread. Think about it: Can I use a subthread to execute my delegate Method for me without affecting my main line.
The answer is: yes. In this case, we can create a Thread class Thread or use an asynchronous delegate (Thread pool worker Thread). Here we do not apply to the newly created Thread, because it is not easy to manage.

2. Initial asynchronous Delegation

View Code

// Declare the delegate
Public delegate void DeleMethod (string name );
Class Program
{
Static void Main (string [] args)
{
DeleMethod delemethod = Speaking;
// Execute asynchronous Delegation
Delemethod. BeginInvoke ("Mr. w", null, null );
// Main thread method
Console. WriteLine ("I want to execute the method ....");

}

// Method to be called by Delegate
Static void Speaking (string name)
{
Console. WriteLine ("My name is {0}", name );
// Uses sleep for 3 seconds, and the method for simulating delegated execution is long.
Thread. Sleep (TimeSpan. FromSeconds (3 ));
Console. WriteLine ("the delegate method has been executed! ");
}
}
Copy code

 

Output:
Next I want to execute the method ....
My name is Mr. w.
Copy code

Analysis:
1. What's going on? Why does it seem that the delegate method has not been completed?
A: threads are divided into foreground and background threads. The default thread pool is a background thread. The main thread directly exits the program without considering whether the background thread has been executed. The default Thread of the newly created Thread class is the foreground Thread. The main Thread must wait for the Thread to finish executing and then exit the AppDomain.
Whether the thread is a foreground thread or a background thread depends on the IsBackground attribute.
2. We can use a Console. ReadKey (); to prevent the main thread from exiting the AppDomain.

3. asynchronous delegation with return values
As we all know, sometimes the main thread does not care about the return value of the delegate method at all, so whether or not the return value of the asynchronous delegate can be displayed in my main window is even less concerned, however, the returned values can also solve many problems:
1. As mentioned in the previous blog, non-void delegate methods can return exception information.
2. Some software processes the return value of the delegate method as a parameter of another method.

Code 1:
 

View Code

// Declare the delegate
Public delegate string DeleMethod (string name );
Class Program
{
Static void Main (string [] args)
{
DeleMethod delemethod = Speaking;
// Execute asynchronous Delegation
IAsyncResult result = delemethod. BeginInvoke ("Mr. w", null, null );
String s = delemethod. EndInvoke (result );
// Main thread method
Console. WriteLine ("I want to execute the method ....");
// Prevent the main thread from exiting the program
Console. ReadKey ();
}

// Method to be called by Delegate
Static string Speaking (string name)
{
// Uses sleep for 3 seconds, and the method for simulating delegated execution is long.
Thread. Sleep (TimeSpan. FromSeconds (3 ));
Console. WriteLine ("My name is {0}", name );
Return "The delegate method has been executed! ";
}
}
Copy code
Output:
My name is Mr. w.
Next I want to execute the method ....
Copy code

Note:
According to our theory, the output result is as follows:

Next I want to execute the method ....
My name is Mr. w.
Copy code

 

Why is the opposite result?
Answer:
1. Because asynchronous delegation starts with the BeginInvoke () method and ends with EndInvoke.
2. the return value of asynchronous delegation is returned by EndInvoke.

Therefore, if you want to return a value, you must write EndInvoke ();, but someone has to ask, if you call the EndInvoke () method in the main thread, the main thread does not need to wait until the sub-thread completes execution to execute the following code. What is the difference between this and synchronous execution? So Asynchronization is meaningless.

Correct! Completely correct, but is there any result that can be asynchronously delegated without affecting the main thread mode.

4. Let's talk about how to get the return value without affecting the main thread.

To solve this problem, you must understand the BeginInvoke () method of asynchronous delegation.

1. The easiest thing to forget about BeginInvoke () is to execute the delegate variable of the BeginInvoke () method. The preceding variable delemethod must be a unicast delegate, that is, only one method can be bound. For multicast delegation, traverse all methods and use Asynchronous delegation to traverse and query my previous blog.
2. the BeginInvoke () method has four parameters. The first two are the same as the parameters of your delegate method. The last two parameters are AsyncCallback and Object, asyncCallback is a delegate type used to automatically call the method when asynchronous execution is complete. The last parameter Object type can be obtained through the AsyncState attribute of the AsyncResult type variable, or the AsyncState attribute of the IAsyncResult type variable.
3. The BeginInvoke () method returns an IAsyncResult interface, which is essentially an object of AsyncResult. Use AsyncDelegate of AsyncResult to obtain the delemthod delegate object, and then call the EndInvoke () method on it.

Are you confused? Based on the Case Study:
Code 1:

View Code
Output:
Next I want to execute the method ....
My name is Mr. w.
The delegate method has been executed!
Copy code

First look at the results: the results are in line with our theory.
Analysis:
1. We all know that if an asynchronous delegate wants to return a value, the EndInvoke () method must be called, but which delegate variable is used for calling?
The last parameter of the. BeginInvoke () method is the AsyncState of the IAsyncResult type variable returned by BeginInvoke (). In this way, the object of the delegate variable is obtained, such as Code 1.
Or use AsyncDelegate of AsyncResult to obtain the delemethod delegate object, and then call the EndInvoke () method on it. For example, code 2
Code 2:
 

View Code
Output:
Current thread ID: 1
Next I want to execute the method ....
Current thread ID: 3
My name is Mr. w.
Current thread ID: 3
The delegate method has been executed!
Current thread ID: 3
Copy code

Summary: asynchronous delegation is introduced here. The specific application depends on your understanding of the thread. Sometimes, synchronization is faster than Asynchronization. Sometimes it is more asynchronous than synchronous blocks, depending on the specific situation.

Books are books, you are you, and text copying is a book. You must understand it yourself, even if you have a wrong understanding. Next, let's talk about asynchronous delegation. The individual is not deeply involved in. net and has little experience. If not, I hope you can point it out.
For the thread, I don't want to talk about it. I can search for the "thread and thread" in the blog garden, which is quite detailed. This blog post is intended for: friends who know some threads but are vague about asynchronous delegation.
In fact, this asynchronous delegate should be discussed together with the Thread. Why do we like this asynchronous delegate for three reasons:
. The execution of the main thread is not affected.
. Reasonably use ThreadPool thread pool threads
Asynchronous delegation is essentially a worker thread that calls the thread pool. It is managed by the thread pool in a unified manner to avoid the headache of creating and canceling threads.

1. Traditional synchronous delegation (the method for simulating delegation takes a long time to execute)
The method used to simulate the delegate is executed for a long time: Thread. Sleep (TimeSpan. FromSeconds (3 ));

View Code

// Declare the delegate
Public delegate void DeleMethod (string name );
Class Program
{
Static void Main (string [] args)
{
DeleMethod delemethod = Speaking;
Delemethod ("Mr. w ");
Console. WriteLine ("I want to execute the method ....");

}

// Method to be called by Delegate
Static void Speaking (string name)
{
Console. WriteLine ("My name is {0}", name );
// Uses sleep for 3 seconds, and the method for simulating delegated execution is long.
Thread. Sleep (TimeSpan. FromSeconds (3 ));
Console. WriteLine ("the delegate method has been executed! ");
}
Copy code

Analysis:
. According to F11, everyone can analyze it by themselves. Main () is the start of all programs. The program calls the Speaking () method to sleep for 3 seconds, this affects the method execution time below the main thread.
From start to end, the program has only one thread. Think about it: Can I use a subthread to execute my delegate Method for me without affecting my main line.
The answer is: yes. In this case, we can create a Thread class Thread or use an asynchronous delegate (Thread pool worker Thread). Here we do not apply to the newly created Thread, because it is not easy to manage.

2. Initial asynchronous Delegation

View Code

// Declare the delegate
Public delegate void DeleMethod (string name );
Class Program
{
Static void Main (string [] args)
{
DeleMethod delemethod = Speaking;
// Execute asynchronous Delegation
Delemethod. BeginInvoke ("Mr. w", null, null );
// Main thread method
Console. WriteLine ("I want to execute the method ....");

}

// Method to be called by Delegate
Static void Speaking (string name)
{
Console. WriteLine ("My name is {0}", name );
// Uses sleep for 3 seconds, and the method for simulating delegated execution is long.
Thread. Sleep (TimeSpan. FromSeconds (3 ));
Console. WriteLine ("the delegate method has been executed! ");
}
}
Copy code

 

Output:
Next I want to execute the method ....
My name is Mr. w.
Copy code

Analysis:
1. What's going on? Why does it seem that the delegate method has not been completed?
A: threads are divided into foreground and background threads. The default thread pool is a background thread. The main thread directly exits the program without considering whether the background thread has been executed. The default Thread of the newly created Thread class is the foreground Thread. The main Thread must wait for the Thread to finish executing and then exit the AppDomain.
Whether the thread is a foreground thread or a background thread depends on the IsBackground attribute.
2. We can use a Console. ReadKey (); to prevent the main thread from exiting the AppDomain.

3. asynchronous delegation with return values
As we all know, sometimes the main thread does not care about the return value of the delegate method at all, so whether or not the return value of the asynchronous delegate can be displayed in my main window is even less concerned, however, the returned values can also solve many problems:
1. As mentioned in the previous blog, non-void delegate methods can return exception information.
2. Some software processes the return value of the delegate method as a parameter of another method.

Code 1:
 

View Code

// Declare the delegate
Public delegate string DeleMethod (string name );
Class Program
{
Static void Main (string [] args)
{
DeleMethod delemethod = Speaking;
// Execute asynchronous Delegation
IAsyncResult result = delemethod. BeginInvoke ("Mr. w", null, null );
String s = delemethod. EndInvoke (result );
// Main thread method
Console. WriteLine ("I want to execute the method ....");
// Prevent the main thread from exiting the program
Console. ReadKey ();
}

// Method to be called by Delegate
Static string Speaking (string name)
{
// Uses sleep for 3 seconds, and the method for simulating delegated execution is long.
Thread. Sleep (TimeSpan. FromSeconds (3 ));
Console. WriteLine ("My name is {0}", name );
Return "The delegate method has been executed! ";
}
}
Copy code
Output:
My name is Mr. w.
Next I want to execute the method ....
Copy code

Note:
According to our theory, the output result is as follows:

Next I want to execute the method ....
My name is Mr. w.
Copy code

 

Why is the opposite result?
Answer:
1. Because asynchronous delegation starts with the BeginInvoke () method and ends with EndInvoke.
2. the return value of asynchronous delegation is returned by EndInvoke.

Therefore, if you want to return a value, you must write EndInvoke ();, but someone has to ask, if you call the EndInvoke () method in the main thread, the main thread does not need to wait until the sub-thread completes execution to execute the following code. What is the difference between this and synchronous execution? So Asynchronization is meaningless.

Correct! Completely correct, but is there any result that can be asynchronously delegated without affecting the main thread mode.

4. Let's talk about how to get the return value without affecting the main thread.

To solve this problem, you must understand the BeginInvoke () method of asynchronous delegation.

1. The easiest thing to forget about BeginInvoke () is to execute the delegate variable of the BeginInvoke () method. The preceding variable delemethod must be a unicast delegate, that is, only one method can be bound. For multicast delegation, traverse all methods and use Asynchronous delegation to traverse and query my previous blog.
2. the BeginInvoke () method has four parameters. The first two are the same as the parameters of your delegate method. The last two parameters are AsyncCallback and Object, asyncCallback is a delegate type used to automatically call the method when asynchronous execution is complete. The last parameter Object type can be obtained through the AsyncState attribute of the AsyncResult type variable, or the AsyncState attribute of the IAsyncResult type variable.
3. The BeginInvoke () method returns an IAsyncResult interface, which is essentially an object of AsyncResult. Use AsyncDelegate of AsyncResult to obtain the delemthod delegate object, and then call the EndInvoke () method on it.

Are you confused? Based on the Case Study:
Code 1:

View Code
Output:
Next I want to execute the method ....
My name is Mr. w.
The delegate method has been executed!
Copy code

First look at the results: the results are in line with our theory.
Analysis:
1. We all know that if an asynchronous delegate wants to return a value, the EndInvoke () method must be called, but which delegate variable is used for calling?
The last parameter of the. BeginInvoke () method is the AsyncState of the IAsyncResult type variable returned by BeginInvoke (). In this way, the object of the delegate variable is obtained, such as Code 1.
Or use AsyncDelegate of AsyncResult to obtain the delemethod delegate object, and then call the EndInvoke () method on it. For example, code 2
Code 2:
 

View Code
Output:
Current thread ID: 1
Next I want to execute the method ....
Current thread ID: 3
My name is Mr. w.
Current thread ID: 3
The delegate method has been executed!
Current thread ID: 3
Copy code

Summary: asynchronous delegation is introduced here. The specific application depends on your understanding of the thread. Sometimes, synchronization is faster than Asynchronization. Sometimes it is more asynchronous than synchronous blocks, depending on the specific situation.

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.