As the C# asynchronous program development series deepens, you will find that writing asynchronous programs becomes easier. The development of things is like this, from simple to complex and then to simple.
In C# 5.0, we can achieve fast asynchronous program development through the async and await keywords, as follows:
##
static void Main(string[] args) { var task = GetResultAsyc(); Console.WriteLine(String.Format("Main 线程:{0}", Thread.CurrentThread.ManagedThreadId)); for (int i = 0; i < 100; i++) { Console.Write("."); Thread.Sleep(10); } Console.WriteLine(); Console.WriteLine(String.Format("Main 线程:{0},获取异步执行结果:{1}", Thread.CurrentThread.ManagedThreadId, task.Result)); Console.ReadLine(); } private static async Task<int> GetResultAsyc() { Console.WriteLine(String.Format("线程:{0}", Thread.CurrentThread.ManagedThreadId)); var result = await Task.Run(() => { Console.WriteLine(String.Format("Task 线程:{0}", Thread.CurrentThread.ManagedThreadId)); Thread.Sleep(5000); return 10; }); return result; }
async represent methods that can be called asynchronously. The name of this method should end with Async.
2. If there is a return value after the asynchronous method is executed, the return type of the asynchronous method should be Taskasync, you can start Task or call other asynchronous methods. If you use await before calling, the calling thread will return directly and execute its subsequent steps. code. The called program behind await is executed in one or more (depending on nesting and other factors) new threads.
4. After the function in the new thread is executed, the return result will be returned by the new thread (this is not a return to the calling thread, but the new thread sets the Task.Result obtained by the calling thread). 5. When using await Task or Task.Result in the calling thread, the calling thread will wait (block) for the new thread to complete execution and obtain the result. The program output is as follows: As we introduced before, related IO, Net, etc. after .Net Framework 4.5 all support async and await Calling, all C# asynchronous program development based on the above version will be greatly simplified. Now .Net Web development has begun to popularize asynchronous programming, which has helped improve Web IO throughput.The above is the detailed content of Asynchronous programming in C# 4A case analysis of async and await asynchronous program development. For more information, please follow other related articles on the PHP Chinese website!