Thread is also crazy ----- asynchronous programming, thread ----- asynchronous

Source: Internet
Author: User

Thread is also crazy ----- asynchronous programming, thread ----- asynchronous
Preface

This section describes basic knowledge about tasks, Async, and Await in asynchronous programming.

What is asynchronous?

Asynchronous processing does not block the current thread to wait for processing to complete, but allows subsequent operations until other threads finish processing and calls back to notify this thread.

Asynchronous and Multithreading

Similarities: Avoid calling thread blocking to improve software responsiveness.

Differences:

Asynchronous operations require no additional thread burden and Use callback for processing. When well designed, the processing function does not need to use shared variables (even if it cannot be completely used, at least the number of shared variables can be reduced) to reduce the possibility of deadlocks. The use of the keyword Async and Await after C #5.0. NET4.5 makes asynchronous programming very simple.

The processing program in multiple threads is still executed in sequence, but the disadvantage of Multithreading is also obvious. The use (abuse) of threads will put an extra burden on the system for context switching. In addition, shared variables between threads may cause deadlocks. Asynchronous application scenarios and principles

Asynchronization is mainly used for IO operations, database access, disk operations, Socket access, and HTTP/TCP network communication.

Cause: I/O operations do not require excessive CPU computing. The data is mainly processed through disks. If synchronous communication cannot end, more thread resources need to be created, frequent data context switching of threads is also a waste of resources. IO operations do not need to be handled by a separate thread.

Example:

Operation: the server receives an HTTP request to operate the database and then returns

Synchronization:

Asynchronous

Task

Before using a task, most of the calls to the thread use the static method QueueUserWorkItem provided by the thread pool. However, this function has many restrictions, the biggest problem is that there is no internal mechanism to let developers know when the operation is completed, nor can the mechanism get the return value when the operation is completed. Microsoft introduces the concept of task to solve this problem.

First, construct a Task <TResult> object and pass the return value to the TResult object. Wait for the Task to start and return the result. The sample code is as follows:

1 static void Main (string [] args) 2 {3 Console. writeLine ("START computing"); 4 // ThreadPool. queueUserWorkItem (Sum, 10); 5 Task <int> task = new Task <int> (Sum, 100); 6 task. start (); 7 // display waiting for result 8 task. wait (); 9 // when the Result is called, Wait for the return Result 10 Console. writeLine ("program result: Sum = {0}", task. result); 11 Console. writeLine ("program ended"); 12 Console. readLine (); 13} 14 15 public static int Sum (object I) 16 {17 var sum = 0; 18 for (var j = 0; j <= (int) I; j ++) 19 {20 Console. write ("{0} +", sum); 21 sum + = j; 22} 23 Console. writeLine ("= {0}", sum); 24 return sum; 25}

In addition to wait waiting for a single task, the Task also provides waiting for multiple tasks, WaitAny and WaitAll, which stop calling threads until all the task objects in the array are completed.

Cancel task

Canceling a task also uses. NET Framework standard cancel operation mode, first create a CancellationTokenSource object, then add the CancellationToken parameter to the function, pass the Token of CancellationTokenSource to the method, then, call IsCancellationRequested to determine whether the value has been canceled.

1 static void Main (string [] args) 2 {3 Console. writeLine ("START computing"); 4 // ThreadPool. queueUserWorkItem (Sum, 10); 5 var ctx = new CancellationTokenSource (); 6 var task = new Task <int> () => Sum (ctx. token, 100000); 7 task. start (); 8 // display pending results 9 // task. wait (ctx. token); 10 Thread. sleep (1000); 11 ctx. cancel (); 12 // wait for the return Result 13 Console when the Result is called. writeLine ("program result: Sum = {0}", task. result); 14 Console. writeLine ("program ended"); 15 Console. readLine (); 16} 17 18 public static int Sum (CancellationToken cts, object I) 19 {20 var sum = 0; 21 for (var j = 0; j <= (int) I; j ++) 22 {23 if (cts. isCancellationRequested) return sum; 24 Thread. sleep (50); 25 Console. write ("{0} +", sum); 26 sum + = j; 27} 28 Console. writeLine ("= {0}", sum); 29 return sum; 30}
The new task is automatically started after the task is completed.

In actual development applications, another task is started immediately after the task is completed, and the thread cannot be blocked. If the result is called before the task is completed, the program is blocked, you cannot view the progress of the TASK. The TASK provides the method ContinueWith, which does not block any threads. When the first TASK is completed, the second TASK is started immediately.

1 static void Main (string [] args) 2 {3 Console. writeLine ("START computing"); 4 // ThreadPool. queueUserWorkItem (Sum, 10); 5 var ctx = new CancellationTokenSource (); 6 var task = new Task <int> () => Sum (ctx. token, 100000); 7 task. start (); 8 var cwt = task. continueWith (p => 9 {10 Console. writeLine ("task result = {0}", task. result); 11}); 12 // display waiting for the Result to be obtained 13 // task. wait (ctx. token); 14 Thread. sleep (1000); 15 ctx. cancel (); 16 // wait for the return Result 17 Console when the Result is called. writeLine ("program result: Sum = {0}", task. result); 18 Console. writeLine ("program ended"); 19 Console. readLine (); 20} 21 22 public static int Sum (CancellationToken cts, object I) 23 {24 var sum = 0; 25 for (var j = 0; j <= (int) I; j ++) 26 {27 if (cts. isCancellationRequested) return sum; 28 Thread. sleep (50); 29 Console. write ("{0} +", sum); 30 sum + = j; 31} 32 Console. writeLine ("= {0}", sum); 33 return sum; 34}
Simple use of Async & Await

The main purpose of Using Async & Await is to facilitate asynchronous operations, because. before net 4.0, asynchronous operations were complicated, mainly by calling the asynchronous callback method provided by Microsoft for programming. If you need to implement your own method, it would be a headache ,. each version of net has its own proprietary technology, such. delegate in NET1.1 ,. generic in NET2.0 ,. in NET3.0 ,. dynimac in NET4.0 ,. net4.5 refers to asynchronous programming. You only need to understand TASK + asynchronous functions to implement asynchronous programming.

Async: tells CLR that this is an asynchronous function.

Await: Asynchronously processes the functions returned by the Task <TResult>.

 

Purpose: To obtain the JS Code of the website and display it on the page.

1 private static async Task <string> DownloadStringWithRetries (string uri) 2 {3 using (var client = new HttpClient () 4 {5 // 1 second before 1st retries, 2 seconds for 2nd times and 4 seconds for 3rd Times. 6 var nextDelay = TimeSpan. FromSeconds (1); 7 for (int I = 0; I! = 3; ++ I) 8 {9 try10 {11 return await client. getStringAsync (uri); 12} 13 catch14 {15} 16 await Task. delay (nextDelay); 17 nextDelay = nextDelay + nextDelay; 18} 19 // The Last retry to let the caller know the error message. 20 return await client. GetStringAsync (uri); 21} 22}
1 static void Main (string [] args) 2 {3 Console. writeLine ("Get Baidu data"); 4 ExecuteAsync (); 5 Console. writeLine ("thread end"); 6 Console. readLine (); 7} 8 9 public static async void ExecuteAsync () 10 {11 string text = await DownloadStringWithRetries ("http://wwww.baidu.com"); 12 Console. writeLine (text); 13}

The running result shows that Baidu data is obtained first, the thread ends, and the JS Code is displayed. This is because a new thread is enabled asynchronously and does not cause thread blocking.

 

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.