Why async is required, Async is critical for activities that can be blocked (for example, when an application accesses the Web). Access to Web resources is sometimes slow or delayed.
This section will take you through the steps to understand async and await.
During the period there will be
HelloWorld, Introduction to the principle, asynchronous will increase the speed of the program ,async and await,MVC in the asynchronous action, As well as thread safety and semaphores commonly involved in threading, and the asynchronous API provided by Microsoft
Recommended first look at the top, learn faster!
Hello World
static void Main (string[] args) { new Thread (Test) {IsBackground = false}. Start (); . Net has provided the most basic API at 1.0. ThreadPool.QueueUserWorkItem (o = Test ()); The thread pool takes the idle thread to execute the delegate (method) Task.run (Action) Test); . Net 4.0 or more available Console.WriteLine ("Main Thread"); Console.ReadLine (); } static void Test () { thread.sleep (); Console.WriteLine ("Hello World"); }
Principle
In fact, regardless of task,threadpool, the essence is ultimately thread. Just Microsoft helped us simplify the complexity of threading control.
Thread pools are some of the pre-defined threads in the CLR. The thread pool that the task takes, except in syntax, can be very convenient to take the return value.
Does async increase the speed of your program?
Multithreading increases the efficiency of the program and does not increase the speed of the operation.
This is like a task that takes 1 hours to the front desk. 10 minutes from reception.
Call the manager and have him arrange for a person to work for 30 minutes (new Thread ()) and he will do the remaining 20 minutes. (Creates threads, takes time, memory resources)
Or, from a nearby idle colleague (ThreadPool or Task), pull a person over for 30 minutes. He did the rest of the 20 minutes. (Less time required, resources exist)
As seen from the above, Asynchrony can make a task longer. Resources consume more. However, you can have the foreground (UI thread) idle and follow the lead (user) command.
Async and await are just a sign
First Look at a demo,
static void Main (string[] args) { task.run () = //asynchronously begins execution of { thread.sleep (); Perform some tasks asynchronously Console.WriteLine ("Hello World"); Execute completion token asynchronously }); Thread.Sleep (1100); The main thread performs some task Console.WriteLine ("Main thread"); Main thread Completion tag console.readline (); }
The results of the discovery are:
This is normal. But what do we want to do with the main thread completion tag, without changing the main thread and task tasks?
Using await and Async
static void Main (string[] args) { Say (); Because main cannot use the async tag console.readline (); } Private async static void Say () { var t = Testasync (); Thread.Sleep (1100); The main thread performs some task Console.WriteLine ("Main thread"); Main thread Completion Tag Console.WriteLine (await T); Await main thread waits for asynchronous return result } static async task<string> Testasync () { return await task.run (() = > { thread.sleep (+); Perform some tasks asynchronously return "Hello World"; Execute completion token asynchronously });
1. Any method that uses the AWAIT keyword must be marked with an async tag.
2.async means there is an async method inside the method, and an await means waiting for the Async method to finish executing and fetching the return value.
3. Call the Async method, and the thread executes immediately. Await just shows the waiting thread to end.
Asynchronous action in MVC
Why use multithreading to "spin down", since multithreading doesn't improve speed, and every time an ASP is requested to launch a new thread?
To improve the throughput of your site.
In MVC, if an asynchronous action is taken, it is performed as follows.
1. The request arrives at the Iis,iis application pool to allocate a worker thread to respond to the request.
A 2.worker thread that performs an asynchronous operation invokes the CLR thread pool threading.
3. Release the worker thread in response to other requests.
4. When the asynchronous operation finishes executing, the W3WP (application pool process) assigns a worker thread to continue responding.
In the above usage scenario, you get two worker threads, which may or may not be the same as the two fetch threads. If there is a time-consuming task, it is highly recommended to convert the synchronization request to asynchronous.
Thread Safety and semaphores
Let's start with an example of a thread that is unsafe.
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 ($); Console.WriteLine ("Execution Complete"); Iscomplete = true; } } public static bool Iscomplete {get; set;}
The result of the above execution is that the thread is unsafe. (Multithreaded access to the same piece of code produces indeterminate results.) )
How to solve, involving the concept of the thread lock. The thread lock allows multiple threads to access, allowing only one thread to enter at a time.
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) //Lock must be a reference type. Because in a static method, the static reference type is locked. { if (! Iscomplete) { //todo other thread.sleep ($); Console.WriteLine ("Execution Complete"); Iscomplete = True;}} }
Signal Volume
The technology of the thread lock allows a piece of code to enter only one thread. The presence of semaphores is the same piece of code that specifies multiple threads to enter.
Signal Volume (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); c5/>} Console.ReadLine (); } Private async static void Test (Object i) { Console.WriteLine ("Ready to execute" + i); Await Slim. Waitasync (); Console.WriteLine ("Start Execution" + i); Todo other await task.delay (+); Console.WriteLine ("Execution End" + i); Slim. Release (); }
Above execution results
The APIs listed in the. NET Framework 4.5 and Windows runtimes contain methods that support asynchronous programming.
application area |
Supported APIs that contain async methods |
Web Access |
Httpclient,syndicationclient |
| Use file |
storagefile, StreamWriter, streamreader, XmlReader ">storagefile, StreamWriter, StreamReader, XmlReader |
Working with Images |
MediaCapture, Bitmapencoder, Bitmapdecoder |
WCF programming |
Synchronous and asynchronous operations |
Never, C
This article link: http://www.cnblogs.com/neverc/p/4368821.html
This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.
If you feel that there is help, you can click on the lower right corner of the "recommendation", hoping to continue to bring good technical articles for everyone! Want to make progress with me? Then "pay attention" to me.
[C #] Talk about Async programming async await