With the depth of the C # asynchronous Program Development series, you'll find it easier to write asynchronous programs. The development of things is such a law, from simple to complex to simple.
In C # 5.0, we can quickly develop asynchronous programs with the async and await keywords, as follows:
static void Main (string[] args) {var task = getresultasyc (); Console.WriteLine (String.Format ("Main thread: {0}", Thread.CurrentThread.ManagedThreadId)); for (int i = 0; i < 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. The method with async notation Represents a method that can be called asynchronously, and the name of this method should end with async.
2. If the Async method executes with a return value, the return type of the Async method should be the type tresult> of the task< return value. If there is no return value, it should be a task.
3. In the async Callout method, you can open a task or call another async method, and use await before the call will return and execute its subsequent code directly. The callee behind the await is executed in one or more new threads, depending on the circumstances of the nesting.
4. After the function in the new thread is finished, return Result will be returned by the new thread (this is not the calling thread, but the task.result that the calling thread gets from the new thread).
5. When an await Task or task.result is used in the calling thread, the calling thread waits (blocks) for the new thread to complete and obtain the result.
The program output is as follows:
As we described earlier, the. Net Framework4.5 post-related io,net and so on are all supported for async and await calls, and all of the C # asynchronous program development based on the above version will be much simpler.
The popularity of asynchronous programming has now started in. Net Web hair, which is helping to improve Web IO throughput.