码迷,mamicode.com
首页 > 其他好文 > 详细

async,await.task

时间:2020-03-18 20:24:45      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:style   event   line   object   img   ons   string   str   代码   

 

示例代码:

        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

标签:style   event   line   object   img   ons   string   str   代码   

原文地址:https://www.cnblogs.com/JinweiChang/p/12519642.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!