async 和 await 的用法示例

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

namespace ConsoleApp2
{
    class Program
    {
        static  void Main()
        {
            Console.WriteLine("Without async,the spend time is ");
            StopWatchTool(GetClientInformationWithoutAsync);
            Console.WriteLine("With async,the spend time is ");
            StopWatchTool(GetClientInformationWithAsync);
            Console.Read();
        }
        private static void StopWatchTool(Action action)
        {
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            action();
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);
        }
        private static void GetClientInformationWithoutAsync()
        {
            var location = Client.GetLocation();
            var weather = Client.GetWeather();
            Console.WriteLine(location + " " + weather);
        }
        private async static void GetClientInformationWithAsync()
        {
            var location2 = Client.GetLocationTaskAsync();
            var weather2 = Client.GetWeatherTaskAsync();
            await Task.WhenAll(location2, weather2);
            Console.WriteLine(location2.Result + " " + weather2.Result);
        }

    }
    class Client
    {
        public static String GetWeather()
        {
            Thread.Sleep(1000);
            return "Sunny";
        }
        public  static Task<String> GetWeatherTaskAsync()
        {
            var a = new Task<string>(GetWeather);
            a.Start();
            return a;
        }
        public static String GetLocation()
        {
            Thread.Sleep(2000);
            return "Pukou";
        }
        public static Task<String> GetLocationTaskAsync()
        {
            var a= new Task<string>(GetLocation);
            a.Start();
            return a;
        }

    }
}

  

posted on 2018-01-11 15:31  方辰  阅读(201)  评论(0编辑  收藏  举报

导航