Async和await关键字的用法

async & await 的前世此生(Updated)

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

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

image image
static void Main(string[] args)
        {
            // 异步方式
            Console.WriteLine("\n异步方式测试开始!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;
        }

更推荐这种写法async

image
相关文章
相关标签/搜索