C # asynchronous programming 4 async and await asynchronous program development,
With the development of C # asynchronous program series, you will find it easier to write asynchronous programs. The development of things is such a rule, from simplicity to complexity to simplicity.
In C #5.0, we can use async and await keywords to implement fast asynchronous program development, as shown below:
Static void Main (string [] args) {var task = GetResultAsyc (); Console. writeLine (String. format ("Main Thread: {0}", Thread. currentThread. managedThreadId); for (int I = 0; I <100; I ++) {Console. write (". "); Thread. sleep (10);} Console. writeLine (); Console. writeLine (String. format ("Main Thread: {0}, get asynchronous execution result: {1}", Thread. currentThread. managedThreadId, task. result); Console. readLine ();} private static async Task <int> GetResultAsyc () {Console. writeLine (String. format ("Thread: {0}", Thread. currentThread. managedThreadId); var result = await Task. run () => {Console. writeLine (String. format ("Task Thread: {0}", Thread. currentThread. managedThreadId); Thread. sleep (5000); return 10;}); return result ;}
Program description:
1. Representation Using async AnnotationYesAsynchronous call method. The name of this method should end with Async.
2. If a return value is returned after an Asynchronous Method is executed, the return type of the asynchronous method should be Task <returned type TResult>. If no return value is returned, it should be a Task.
3. You can enable the Task or call other asynchronous methods in the async annotation method. When await is used before the call, the calling thread will directly return and execute its subsequent code. The called program after await is executed in one or more new threads (depending on factors such as nesting.
4. After the functions in the new thread are executed, the return result will be returned by the new thread (not the call thread, but the Task. Result obtained by the new thread ).
5. When await Task or Task. Result is used in the call thread, the call thread waits for (blocking) The execution of the new thread to complete and obtain the Result.
The program output is as follows:
As we introduced earlier, IO and Net related after. Net Framework4.5 have supported async and await calls. All C # asynchronous program development based on the above version will be much simpler.
Now, asynchronous programming has been popularized in. Net Web development, which helps improve Web I/O throughput.
The asynchronous programming series has come to an end. This series of articles will be helpful to anyone who wants to learn about C # asynchronous programming. I believe that with the development and opening up of C #, C # will surely bloom more brilliantly.