C# async await 举个栗子

首先,async 和 await 代表异步执行和等待。

async是一个标记,告诉编译器,我可能是一个异步方法。

await 代表等待,告诉编译器,这里等我返回结果。

下面,我们简单说一下。

一 , 首先我们看一下普通程序

static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
 
            MyTest();
            Thread.Sleep(5000);
            Console.WriteLine("Completed");
 
            sw.Stop();
            Console.WriteLine(sw.Elapsed.Seconds);
            Console.ReadKey();
        }
 
        public static void MyTest()
        {
            Test1();
        }
 
        public static void Test1()
        {
            Thread.Sleep(5000);
            Console.WriteLine("Test1");
        }

查看结果:

结论:

由于Main()和MyTest()都存在 Thread.Sleep(5000),所以总共耗时10秒。

二 ,下面使用await / async

static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
 
            MyTest();
            Thread.Sleep(5000);
            Console.WriteLine("Completed");
 
            sw.Stop();
            Console.WriteLine("耗时:"+sw.Elapsed.Seconds);
            Console.ReadKey();
        }
 
        public static async void MyTest()
        {
            await Test1();
        }
 
        public async static Task Test1()
        {
            await Task.Delay(5000);
            Console.WriteLine("Test1");
        }

查看结果:

结论:

运气不错,运行了2次。

因为Task异步处理,所以出现了不太一样的结果。

通过我们这个看出来主线程在5秒就结束了,而线程也在5秒左右结束了。

三 , 最后来个彩蛋,疏导和理解一下运行

static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
 
            MyTest();
            Thread.Sleep(3000);
            Console.WriteLine("Completed");
 
            sw.Stop();
            Console.WriteLine("耗时:"+sw.Elapsed.Seconds);
            Console.ReadKey();
        }
 
 
        public static async void MyTest()
        {
            var q = Test1();
            Console.WriteLine("==============");
            var q1 = Test2();
            Console.WriteLine(await q);
            Console.WriteLine(await q1);
        }
 
 
 
        public static async Task<string> Test1()
        {
            await Task.Delay(5000);
            return "12333";
        }
 
        public static async Task<string> Test2()
        {
            await Task.Delay(3000);
            return "hello";
        }

查看结果:

 

结论:

主程序运行

1 找到MyTest的"==========",输出了,

2 这个时候由于MyTest中q和q1在等待返回,

主程序继续执行下去,输出了"Completed"

3 这里很好理解,输出"耗时:3"

4 为什么把他们都设置为步骤4???因为await阻塞了主程序,在等待返回。

可是!虽然Test1耗时5秒,而Test2耗时3秒。但Test2还是要等待Test1完成才能输出,因为主程序因为await阻塞了

(如果你把Test1改成1秒,效果就明显了。)




原文地址:https://www.cnblogs.com/hanjun0612/p/11103699.html