. Net asynchronous programming details,. net asynchronous explanation

Source: Internet
Author: User

. Net asynchronous programming details,. net asynchronous explanation

I recently read some articles about. Net multi-thread asynchronous programming. Let's take a look at this time!

There are many ways to implement asynchronous programming. This article mainly chooses four methods to give an overview and talk about some of your understanding!

Method 1: use Asynchronous delegation.

We know that C # dynamically generates two methods when processing the delegate Keyword: BeginInvoke () and EndInvoke (). The objects returned by the BeginInvoke () method implement the IAsyncResult interface, while the EndInvoke () method requires an IAsyncResult type as the parameter. Therefore, the IAsyncResult object returned by the BeginInvoke () method allows the calling thread to obtain the results returned by the asynchronous method through the EndInvoke () method later. For a more intuitive understanding, the following is an example!

 

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace test1 {class Program {static void Main (string [] args) {Async ();} /// <summary> /// define a delegate /// </summary> /// <param name = "x"> </param> /// <param name = "y"> </param> // <returns> </returns> private delegate int DelegaIn (int x, int y); private static void Async () {// output the ID of the thread being executed C Onsole. writeLine ("output thread ID:" + System. threading. thread. currentThread. managedThreadId); // call DelegaIn delegaObj = new DelegaIn (Add) in asynchronous mode; IAsyncResult async = delegaObj. beginInvoke (10, 20, null, null); // The main thread continues to execute other tasks Console. writeLine ("the main thread continues executing other tasks !!! "); Int answer = delegaObj. endInvoke (async); Console. writeLine ("Add method end result:" + answer);} private static int Add (int x, int y) {System. threading. thread. sleep (1000*5); // output thread ID Console. writeLine ("output thread ID:" + System. threading. thread. currentThread. managedThreadId); Console. writeLine ("Start the Add method"); return x + y ;}}}

 

Then let's look at the result:

We can see that the console first outputs the ID of the current thread, and then we can see that the Add method is called in asynchronous mode, and the Add method is suspended for 5 seconds using Sleep, however, our program is not blocked and waits, but directly outputs the main thread to continue executing other tasks, and finally waits for the asynchronous return result. In addition, we can see that the Add method actually creates a worker thread maintained by the runtime, and Its thread ID is 3. This is to use Asynchronous Delegation for asynchronous programming. Of course, this is just a simple asynchronous example. Here we will not give an overview of other operations provided by the IAsyncResult interface.

 

Method 2: Use the Thread class under System. Threading.

Use Thread class. In fact, it is to manually create a thread for the current program:

1. Create a ThreadStart (or ParameterizedThreadStart) delegate. And pass the defined method address to the delegate. It is worth noting that the ThreadStart delegate points to a method without return values and parameters. The ParameterizedThreadStart delegate directs to a method with parameters.

2. Create a Thread object and pass the above delegate

3. Call the Thread. Start () method.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace test2 {class Program {static void Main (string [] args) {RunThread ();} private static void RunThread () {// output the execution thread ID Console. writeLine ("output thread ID:" + System. threading. thread. currentThread. managedThreadId); ThreadStart threadStart = new ThreadStart (Prin T); Thread thread = new Thread (threadStart); thread. Start (); // The main Thread continues to execute other tasks Console. WriteLine ("the main thread continues to execute other tasks !!! ");} Private static void Print () {System. threading. thread. sleep (1000*5); // output thread ID Console. writeLine ("output thread ID:" + System. threading. thread. currentThread. managedThreadId); Console. writeLine ("Print method ended ");}}}

The result is similar to that of the preceding asynchronous delegation. This is just how we use the method of manually creating a thread to implement Asynchronization.

 

Method 3: Use the TPL parallel programming library.

At the beginning of Net4.0, Microsoft introduced a new multi-threaded application development method, that is, the TPL parallel programming library. The Task class does not have to deal with threads and thread pools directly.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. threading; namespace test3 {class Program {static void Main (string [] args) {// output the ID Console of the thread being executed. writeLine ("output thread ID:" + System. threading. thread. currentThread. managedThreadId); Task. factory. startNew (Print); // The main thread continues to execute other tasks Console. writeLine ("the main thread continues executing other tasks !!! "); Console. readLine ();} private static void Print () {System. threading. thread. sleep (1000); // output thread ID Console. writeLine ("output thread ID:" + System. threading. thread. currentThread. managedThreadId); Console. writeLine ("Print method ended ");}}}

Result:

The Task class can easily call methods in the next thread, and can be used as a simple alternative to asynchronous delegation !!!

 

Method 3: async and await asynchronous call.

 

Finally, we will introduce the two new keywords under. Net4.5. Async and await.

The async keyword is used to specify that a method or Lambda expression is automatically called asynchronously. Through the async modification method, CLR will create a new execution thread to process the task. When the async method is called, await automatically suspends the current thread until the task is completed and the call thread modified by async is left.

Let's look at a Windows Forms Program.

 

Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. IO; using System. linq; using System. text; using System. threading; using System. threading. tasks; using System. windows. forms; namespace ParallerForm {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void button#click (object sender, EventArgs e) {ProcessFiles (); btnImage1.Text = "main Thread execution completed";} private void ProcessFiles () {Thread. sleep (3000); btnImage. text = "completed thread execution ";}}}

 

When you click the button, it takes three seconds to receive the keyboard input in the text box. The entire form is blocked. Now we can use the async keyword modifier to make it run asynchronously.

Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. IO; using System. linq; using System. text; using System. threading; using System. threading. tasks; using System. windows. forms; namespace ParallerForm {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private async void button#click (object sender, EventArgs e) {await ProcessFiles (); btnImage1.Text = "main thread execution completed";} private async Task ProcessFiles () {await Task. run () => {Thread. sleep (3000); btnImage. text = "completed thread execution ";});}}}

You will find that after you click the button, the form will not be blocked and you can enter a value in the terminal area immediately. Because the async keyword allows it to work in a non-blocking form. When the await keyword is encountered, the thread will be suspended to guide the await task to complete. At the same time, the control is returned to the caller of the method.

Okay! So far, we have introduced four asynchronous programming methods in total. If there is anything wrong with this article, I hope you will not give me any further advice !!!

 



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.