Async和await关键字的用法

async & await 的前世今生(Updated)

1. 方法打上Async关键字, 就可以使用await调用别的Async方法了

2. 记得在需要异步执行的方法里面调用await或者newstask, 才能开启新的线程

image image
static void Main(string[] args)
        {
            // 异步方式
            Console.WriteLine("
异步方式测试开始!main线程id是{0}",System.Threading.Thread.CurrentThread.ManagedThreadId);
            AsyncMethod(0);
            //AsyncMethod_taks(10);
            Console.WriteLine("异步方式测试结束!");
            Console.ReadKey();
        }

        // 异步操作
        private static async void AsyncMethod(int input)
        {
            Console.WriteLine("进入异步操作!线程id是{0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
            var result = await AsyncWork(input);
            Console.WriteLine("最终结果{0}, 线程ID是{1}", result, System.Threading.Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("退出异步操作!");
        }

        // 模拟耗时操作(异步方法)
        private static async Task<int> AsyncWork(int val)
        {
            await Task.Delay(2000);
            for (int i = 0; i < 5; ++i)
            {
                Console.WriteLine("耗时操作{0}, 线程id是 {1}", i, System.Threading.Thread.CurrentThread.ManagedThreadId);
                val++;
            }
            return val;
        }

更推荐这种写法

image  
原文地址:https://www.cnblogs.com/jianjialin/p/5231070.html