异步编程

先实现一个简单的异步方法:(这种方法是:非阻塞的,并行执行的)
asyncRsult方法模拟一些异步操作;
执行到Task.run的时候会返回一个调用者;
在主方法中创建一个等待接受任务结果的对象;

用对象的OnCompleted方法内委托执行获取结果;
当然,这不是最简单的方法
最简单的方法是用关键字async,await
稍后陈述
finished;

    class Program
    {
        static void Main(string[] args)
        {
            var awaiter = asyncResult().GetAwaiter();
            //下面是委托的回调
            awaiter.OnCompleted(
                () =>
                {
                    Console.WriteLine((Int32)awaiter.GetResult());
                }
                );
            Console.WriteLine("sync");
        }
        static Task<int> asyncResult()
        {
            //模拟Io-Bound or Compute-Bound操作
            Thread.Sleep(2000);
            return Task.Run(() => { return 250; }) ;
        }
    }

下面是使用Async await关键字实现的
其实就是简化了OnCompleted

    class Program
    {
        static void Main(string[] args)
        {
            GetResultAsync();
            //下面是委托的回调
            //awaiter.OnCompleted(
            //    () =>
            //    {
            //        Console.WriteLine((Int32)awaiter.GetResult());
            //    }
            //    );
            Console.WriteLine("sync");
            Console.WriteLine("sync");
            Console.WriteLine("sync");
            Console.WriteLine("sync");
            Console.Read();
        }
        static async void GetResultAsync()
        {
            Console.WriteLine( await asyncResult());
        }
        static Task<int> asyncResult()
        {
            //模拟Io-Bound or Compute-Bound操作
            Thread.Sleep(2000);
            return Task.Run(() => { return 250; }) ;
        }
    }
原文地址:https://www.cnblogs.com/liflower/p/13938173.html