[C #] About asynchronous programming async await,

Source: Internet
Author: User

[C #] About asynchronous programming async await,

The reason for the need for Asynchronization is that Asynchronization is critical to activities that may block (for example, when an application accesses the Web. Access to Web resources is sometimes slow or delayed. If such activities are blocked during synchronization, the entire application must wait. During the asynchronous process, the application can continue to execute other tasks that do not depend on Web resources until the tasks are potentially blocked.

This section will show you how to understand async and await.

There will be

Hello World, principle introduction. Will Asynchronization increase the program running speed? async, await, asynchronous Action in MVC, thread security and semaphores commonly involved in threads, and asynchronous API provided by Microsoft

It is recommended that you first read the top and learn faster!

 

Hello World

Static void Main (string [] args) {new Thread (Test) {IsBackground = false }. start ();//. net has provided the most basic API in 1.0. threadPool. queueUserWorkItem (o => Test (); // obtains the idle thread in the thread pool to execute the delegate (method) Task. run (Action) Test );//. net 4.0 or above available Console. writeLine ("Main Thread"); Console. readLine ();} static void Test () {Thread. sleep (1, 1000); Console. writeLine ("Hello World ");}

  

Principle

In fact, whether it is a Task or ThreadPool, it is essentially a Thread. Microsoft helped us simplify the complexity of thread control.

The thread pool is a number of threads defined in CLR in advance. The thread pool of the Task, which is syntactically easy to return.

 

Does Asynchronization increase the program running speed?

Multithreading improves program efficiency and does not increase the running speed.

This is like a task that takes one hour at the front end. When the front-end is complete for 10 minutes

Call the manager and ask him to schedule a person to work for 30 minutes (new Thread (). Then he does the remaining 20 minutes. (Create thread, time required, memory resources)

Or pull a person from a free colleague (ThreadPool or Task) for 30 minutes. The remaining 20 minutes. (The resource already exists because it takes less time)

As shown in the preceding figure, Asynchronization leads to a longer task time. More resource consumption. However, the front-end (UI thread) can be idle and listened to by the leaders (users.

 

 

Async and await are just a tag

First, let's look at a Demo,

Static void Main (string [] args) {Task. run () => // starts asynchronous execution {Thread. sleep (1000); // asynchronously executes some task Console. writeLine ("Hello World"); // asynchronous execution completion mark}); Thread. sleep (1100); // The main thread executes some tasks in the Console. writeLine ("Main Thread"); // The Master Thread completes marking the Console. readLine ();}

The execution result is:

This is normal. But what should we do if we want to execute the main thread to complete the mark without changing the main thread and Task tasks?

 

Use await and async

Static void Main (string [] args) {Say (); // because the Main cannot mark the Console with async. readLine ();} private async static void Say () {var t = TestAsync (); Thread. sleep (1100); // The main thread executes some tasks in the Console. writeLine ("Main Thread"); // The Master Thread completes marking the Console. writeLine (await t); // await main thread waits for asynchronous return result} static async Task <string> TestAsync () {return await Task. run () => {Thread. sleep (1000); // asynchronous execution of some tasks return "Hello World"; // asynchronous execution completion mark });}

1. All methods that use the await keyword must be marked with async.

2. async indicates that there is an Asynchronous Method in the method. When the async method is called, another thread is executed immediately.

3. await only shows waiting for the end of the thread. Await indicates waiting for the Asynchronous Method to be executed and returning the value.

 

 

Asynchronous Action in MVC

Since multithreading cannot improve the running speed, and every request to the Asp.net program is to initiate a new thread, why do we need to use multithreading to reduce the speed "?

To improve the website throughput.

In MVC, asynchronous Action is executed as follows.

1. When a request arrives at IIS, the IIS application pool allocates a worker thread to respond to the request.

2. The worker thread executes asynchronous operations and calls the CLR thread pool thread for processing.

3. Release the worker thread and respond to other requests.

4. After the asynchronous operation is completed, w3wp (application pool process) allocates another worker thread to continue responding.

In the preceding scenario, two worker threads are obtained, which may be the same or different. If there are time-consuming tasks, it is recommended to convert the synchronous request to asynchronous.

 

Thread security and semaphores

Here is an example of thread insecurity.

Static void Main (string [] args) {Task. run (Action) Test); Task. run (Action) Test); Console. readLine ();} private static void Test () {if (! IsComplete) {// todo other Thread. Sleep (500); Console. WriteLine ("execution completed"); IsComplete = true ;}} public static bool IsComplete {get; set ;}

The preceding execution result indicates that the thread is not secure. (Multi-threaded access to the same piece of code produces uncertain results .)

  

How to solve the problem involves the concept of thread lock. The thread lock allows only one thread to enter at a time during multi-thread access.

Thread lock example

Private static readonly object lockObj = new object (); public static bool IsComplete {get; set;} static void Main (string [] args) {Task. run (Action) Test); Task. run (Action) Test); Console. readLine ();} private static void Test () {lock (lockObj) // The lock must be of the reference type. Because the static method locks the static reference type. {If (! IsComplete) {// todo other Thread. Sleep (500); Console. WriteLine ("execution completed"); IsComplete = true ;}}}

  

Semaphores

The thread lock technology allows only one thread to enter a piece of code. If a semaphore exists, multiple threads are specified in the same code.

SemaphoreSlim example

Static readonly SemaphoreSlim slim = new SemaphoreSlim (2); static void Main (string [] args) {for (int I = 0; I <5; I ++) {ThreadPool. queueUserWorkItem (Test, I);} Console. readLine ();} private async static void Test (object I) {Console. writeLine ("ready for execution" + I); await slim. waitAsync (); Console. writeLine ("start execution" + I); // todo other await Task. delay (1000); Console. writeLine ("execution ended" + I); slim. release ();}

Above execution result

 

 

 

The APIS listed in. NET Framework 4.5 and Windows runtime contain methods that support asynchronous programming.

Application Region

Supported APIs that contain asynchronous Methods

Web Access

HttpClient, SyndicationClient

Use Files

StorageFile, StreamWriter, StreamReader, and XmlReader

Use Images

MediaCapture, BitmapEncoder, BitmapDecoder

WCF Programming

Synchronous and asynchronous operations

 

 

 

Author: Never, C

Link: http://www.cnblogs.com/neverc/p/4368821.html

The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.

If you think it is helpful, click [recommendation] in the lower right corner. We hope that we can continue to provide you with good technical articles! Want to make progress with me? Then [follow] Me.

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.