I was from. NET4.0 just out of touch with the. NET environment, so the learning thing is 4.0 and its previous. The era of rapid progress, visual 5.0 also quickly out of it, but has not been to accept new technology. Recently because to learn the Web API, almost finished, but found that 4.5 has been a big line, and then the brain. Async and await are one of them:
This is a two keyword for asynchronous programming. Our traditional asynchronous programming methods are generally thread, ThreadPool, BeginXXX, endxxx and so on. Separate calls, callbacks, the logic of the code is jumping, so it will lead to the idea is not very clear problem, in. NET 4.5, the new async, await keyword, can help us like write synchronous method to write asynchronous method (to ensure that the code is neat and clear).
Let's look at a traditional synchronization Method Example:
1 Static voidMain (string[] args)2 {3 //Synchronization Mode4Console.WriteLine ("sync mode Test starts! ");5Syncmethod (0);6Console.WriteLine ("sync way to end! ");7 Console.readkey ();8 }9 Ten //Synchronous Operation One Private Static voidSyncmethod (intinput) A { -Console.WriteLine ("Enter the sync operation! "); - varresult =syancwork (input); theConsole.WriteLine ("end result {0}", result); -Console.WriteLine ("quit the sync operation! "); - } - + //simulate time-consuming operations (synchronous method) - Private Static intSyancwork (intval) + { A for(inti =0; I <5; ++i) at { -Console.WriteLine ("time-consuming operation {0}", i); -Thread.Sleep ( -); -val++; - } - returnVal; in}
You can see the results of the execution from the diagram on the right, which is a very typical synchronous execution method.
The
Async keyword can be used in the declarations section of a method, a lambda expression, to indicate that this method might contain an await keyword, and only have async to use the await keyword inside it. Task , task < Tresult > , or void . ' data-guid= "b24bb1dd40529caa2edfc875f0777467" > Async methods can have Awaitable " can be of any type (common with Task, task<>), it must expose a getawaiter () The method and returns a valid . More detailed information can be found in the " FAQs on Async and Await", which describes these concepts and considerations.
When an async method, with an await keyword inside it, becomes an async method at compile time, and if there is no await keyword, it will only be executed as a synchronous method. If you are interested in its internal implementation, you can refer to the article " Asynchronous Performance: Understanding the cost of async and Await ", and I believe it is helpful to understand this mechanism in depth.
Now we're trying to use the new async keyword async, await to make an asynchronous call:
Static voidMain (string[] args) { //Async ModeConsole.WriteLine ("\ n Async mode Test begins! "); Asyncmethod (0); Console.WriteLine ("asynchronous way to end! "); Console.readkey (); } //Asynchronous Operation Private Static Async voidAsyncmethod (intinput) {Console.WriteLine ("Enter the asynchronous operation! "); varresult =awaitasyncwork (input); Console.WriteLine ("end result {0}", result); Console.WriteLine ("quit the asynchronous operation! "); } //simulate time-consuming operations (async methods) Private Static Asynctask<int> Asyncwork (intval) { for(inti =0; I <5; ++i) {Console.WriteLine ("time-consuming operation {0}", i); awaitTask.delay ( -); Val++; } returnVal; }
Let's look at the results first, and we find that the time-consuming operation is already asynchronous. The overall process is to call Asyncmethod asynchronously by the main function, not to wait for Asyncmethod to complete and continue execution. The Asyncmethod mode, after being called, starts at the time of the allocation to the timestamp, executes the function body content, and continues to invoke asyncwork asynchronously due to the await Asyncwork statement, but after the await keyword is waiting for asyncwork to complete, And then continue to do it down. So, Ayncwork is also the same, after being called, it starts to start when it is allocated to the time, and performs time-consuming operations.
As you can see, the syntax differences between synchronous and asynchronous programming are further reduced when new keywords are used. With the introduction of. NET 4.5, many new class libraries and existing class libraries support this new type of asynchronous syntax such as HttpClient, Httpserver, MemoryStream ... ), which provide async declarations in a separate way, such as Readasync, WriteAsync, SendAsync, and so on, and the return type is task-and-task<>-asynchronous mode of operation.
Add:
Just now a friend mentioned await Task.delay (100) This statement, this is to let Asyncwork become an async method to add, if you want to do the operation does not support the await adornment what to do, actually very simple, using Task.Factory.StartNew () On the line, for example:
1 //Asynchronous Operation2 Private Static Async voidAsyncmethod (intinput)3 {4Console.WriteLine ("Enter the asynchronous operation! ");5 varresult =awaitTask.Factory.StartNew ((func<Object,int>) SYNCWORK2, input);6Console.WriteLine ("end result {0}", result);7Console.WriteLine ("quit the asynchronous operation! ");8 }9 Ten //simulate time-consuming operations (synchronous method) One Private Static intSYNCWORK2 (Objectinput) A { - intval = (int) input; - for(inti =0; I <5; ++i) the { -Console.WriteLine ("time-consuming operation {0}", i); -Thread.Sleep ( -); -val++; + } - returnVal; +}
In this way, our SYNCWORK2 is actually executed asynchronously, and the result is consistent with the previous Async method, except that the input parameter can only be an object type and requires a type conversion. Also, in addition to startnew, we can create a new task and call run to accomplish the same effect.
For now, this kind of asynchronous work will still cause my use of discomfort, but if in future releases, continue to promote the use, I believe that will soon be proficient, and speed up the writing of code, writing a clear logic code.
Reprint Please specify original site:http://www.cnblogs.com/lekko/archive/2013/03/05/2944282.html
. NET4.5 's first knowledge of async and await