async与await 实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncWaitTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread Id: {0}\r\n", Thread.CurrentThread.ManagedThreadId);

            Test();
            //Thread.Sleep(1);
            Console.WriteLine("Main Thread  execute over !");

            Console.ReadLine();

        }

        static async Task Test()
        {

            Console.WriteLine("Before calling GetName, Thread Id: {0}\r\n", Thread.CurrentThread.ManagedThreadId);
            //此处返回给主线程调用方之后,主线程和Task.Run()内部代码都会继续执行,是同时执行的,不是只有主线程执行而已。
            var name = await GetName();   //我们这里没有用 await,所以下面的代码可以继续执行,

            // 但是如果上面是 await GetName(),下面的代码就不会立即执行,输出结果就不一样了。
            Console.WriteLine("End calling GetName.\r\n");

            Console.WriteLine("Get result from GetName: {0}", name);

        }



        static async Task<string> GetName()
        {

            // 这里还是主线程

            Console.WriteLine("Before calling Task.Run, current thread Id is: {0}", Thread.CurrentThread.ManagedThreadId);

            return await Task.Run(() =>
            {

                //Thread.Sleep(10);

                Console.WriteLine("'GetName' Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);

                return "Jesse";

            });

        }

    }
}

 

posted on 2018-02-11 13:57  itjeff  阅读(226)  评论(0编辑  收藏  举报

导航