C#异步中的Task,async,await

2021-04-26 18:36

阅读:491

标签:pre   时间   sharp   har   ram   date   c#   返回值   thread   

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("我是主线程,线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
            TestAsync();
            Console.ReadLine();
        }

        static async void  TestAsync()
        {
            Console.WriteLine("调用GetReturnResult()之前,线程ID:{0}。当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
            var name = GetReturnResult();
            Console.WriteLine("调用GetReturnResult()之后,线程ID:{0}。当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
           
            //异步回调内容
            //在await以及之后的代码都会阻塞
            Console.WriteLine("得到GetReturnResult()方法的结果:{0}。当前时间:{1}", await name, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
            Console.WriteLine("await之后的内容。当前时间:{0}",  DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
            //异步回调内容
        }

        static async Task GetReturnResult()
        {
            Console.WriteLine("执行Task.Run之前, 线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
            return await Task.Run(() =>
            {
                Thread.Sleep(5000);
                Console.WriteLine("GetReturnResult()方法里面线程ID: {0}", Thread.CurrentThread.ManagedThreadId);
                return "我是返回值";
            });
        }
 
    }

  

C#异步中的Task,async,await

标签:pre   时间   sharp   har   ram   date   c#   返回值   thread   

原文地址:http://www.cnblogs.com/l1pe1/p/7878298.html


评论


亲,登录后才可以留言!