码迷,mamicode.com
首页 > Windows程序 > 详细

C#异步中的Task,async,await

时间:2017-11-22 13:19:13      阅读:252      评论:0      收藏:0      [点我收藏+]

标签: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<string> 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

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