run in this way,   no why,   only for you heart
CSDN博客(点击进入) CSDN
51CTO(点击进入) 51CTO

C# 异步编程

关于“同步”和“异步”介绍可以先看这篇文章:真的理解同步和异步了吗?


使用Task对象来实现多线程async/async方式异步编程:

public class Program
    {
        static int i = 0;
        static void Main(string[] args)
        {
            Console.WriteLine("主线程:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));
            TestAsycAsync();
            i++;
            Console.WriteLine("i="+i);
            Console.WriteLine("主线程结束:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));

            Console.ReadKey();
        }

        public static async Task TestAsycAsync()
        {
            Console.WriteLine("当前线程是:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));
            i = await GetReturnResult();
            Console.WriteLine("i=" + i);
            Console.WriteLine("当前线程是:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));
        }

        static async Task<int> GetReturnResult()
        {
            Console.WriteLine("当前线程是:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));

            //异步开始
            int s = await Task.Run(() =>
            {               
                Console.WriteLine("当前线程是:{0},当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:MM:ss"));
                Thread.Sleep(3000);  //睡眠3s
                i++;
                return i;
            });

            return s;
        }
    }

在这里插入图片描述
执行顺序:
在这里插入图片描述
蓝色标记是主线程,红色标记为异步线程,可以看到当主线执行到await之前程序都是正常运行,在遇到await时,主线程在此方法运行结束,回到原调用的地方,异步线程开始与主线程同时执行。

posted @ 2019-05-19 14:59  _小龙人  阅读(78)  评论(0编辑  收藏  举报