C# 控制台程序验证await立即返回

发布时间 2023-03-27 00:06:02作者: JohnYang819
class Program{

public static volatile bool flag = true;

public static void Main()
        {
            Action a = null;
            Thread t = new Thread(() =>
            {
                Console.WriteLine("before:" + Thread.CurrentThread.ManagedThreadId);
                while (flag)
                {
                    a?.Invoke();
                }
                Console.WriteLine("return:"+Thread.CurrentThread.ManagedThreadId);
            });
            t.Start();
            Console.WriteLine("输入c");
            var s=Console.ReadLine();
            if (s == "c")
            {
                a += TestAsync;
            }
            Console.ReadLine();
        }
        public static async void TestAsync()
        {
            await System.Threading.Tasks.Task.Delay(1);
            flag = false;
            Console.WriteLine("after"+ Thread.CurrentThread.ManagedThreadId);
            
        }

}

output:
```c#
输入c
before:3
c
after8
after12
return:3
after9
after9

解读:
当输入c后,立即返回,打印出"return:3",这里也可以看到立即返回后的线程ID与before:3的ID是一样的,更加确认是返回到了原来的线程,而flag在及时改为false之前,while循环持续进行,并调用TestAsyn,可以发现返回后的线程并不是原来的线程。