async,await.task

 

示例代码:

        private void button16_Click(object sender, EventArgs e)
        {

            Console.WriteLine("按钮开始" + Thread.CurrentThread.ManagedThreadId.ToString());
            task1();
            Console.WriteLine("按钮结束" + Thread.CurrentThread.ManagedThreadId.ToString());

        }

        static async Task task1()
        {

            Console.WriteLine("task1开始" + Thread.CurrentThread.ManagedThreadId.ToString());
            Thread.Sleep(5);
            task2();
            Console.WriteLine("task1结束" + Thread.CurrentThread.ManagedThreadId.ToString());

        }

        static async Task<string> task2()
        {
            Console.WriteLine("task2开始" + Thread.CurrentThread.ManagedThreadId.ToString());
            Thread.Sleep(5);
            await Task.Run(() => { Thread.Sleep(10);
                Console.WriteLine("xxxxxxxxxxxxxxxx" + Thread.CurrentThread.ManagedThreadId.ToString());
            });

            Console.WriteLine("task2结束" + Thread.CurrentThread.ManagedThreadId.ToString());

            return "ddd";
        }

 

async修饰的函数,在被调用时都会开个线程执行,如果加了await当前线程就会等待task2执行完后在往下执行,不加的话,就会并发一起执行。

 

async,await.task

 

上一篇:C# Async Await 异步多线程


下一篇:AwaitAsync(异步和多线程)