. NET asynchronous programming to first recognize async and await

Source: Internet
Author: User

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 void Main (string[] args) 2         {3             //Synchronous Mode 4             Console.WriteLine ("Synchronous mode Test starts! "); 5             syncmethod (0); 6             Console.WriteLine ("Sync Way end! "); 7             Console.readkey (); 8         } 9         //synchronous operation one         private static void Syncmethod (int input)             Console.WriteLine ("Enter the sync operation! ");             var result = syancwork (input);             Console.WriteLine (" Final result {0} ", result);             Console.WriteLine (" Quit the sync operation! ");         }18         //analog time-consuming operation (synchronous method)
         private static int syancwork (int val) (int             i = 0; i < 5; ++i) @                 Console.Write Line ("time-consuming operation {0}", i);                 thread.sleep (+);                 val++;27             }28             return val;29         }

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 &lt; Tresult&gt;, or void." Data-guid= "b24bb1dd40529caa2edfc875f0777467" > Async methods can have a return type of Task, task<>, or void The await keyword is a method or lambda expression for which the return value is a "waiting" type (awaitable), or getawaiter ()   method and return a valid

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 void Main (string[] args)
        {            //Async mode            Console.WriteLine ("\ n Async Test start! ");            Asyncmethod (0);            Console.WriteLine ("Asynchronous Way to end! ");            Console.readkey ();         }          Asynchronous operation        private static async void Asyncmethod (int input)        {            Console.WriteLine ("Enter asynchronous operation! ");            var result = await asyncwork (input);            Console.WriteLine ("Final result {0}", result);            Console.WriteLine ("Quit Async operation! ");        }        Simulate time-consuming operations (async methods)
        private static Async task<int> asyncwork (int val)        {for            (int i = 0; i < 5; ++i)            {                Console.writeli NE ("time-consuming operation {0}", i);                Await Task.delay (+);                val++;            }            return val;        }

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 operation 2         private static async void Asyncmethod (int input) 3         {4             Console.WriteLine ("Enter asynchronous operation! "); 5             var result = await Task.Factory.StartNew ((Func<object, int>) SYNCWORK2, input); 6             Console.WriteLine (" End result {0} ", result); 7             Console.WriteLine ("Quit async operation!") "); 8         } 9         //analog time-consuming operation (synchronous method) one         private static int SyncWork2 (object input), {int '             val = (int.) input;             (int i = 0; i < 5; ++i)             {                 Console.WriteLine ("Time-consuming operation {0}", i);                 thread.sleep (100); 18                 val++;19             }             return val;21         }

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.

. NET asynchronous programming to first recognize async and await

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.