Task.Delay()方法

Task.Delay方法只会延缓异步方法中后续部分执行时间,当程序执行到await表达时,一方面会立即返回调用方法,执行调用方法中的剩余部分,这一部分程序的执行不会延长。另一方面根据Delay()方法中的参数,延时对异步方法中后续部分的执行。

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

namespace Task_Delay
{
    class Program
    {
        static void Main(string[] args)
        {
            Simple ds = new Simple();
            ds.DoRun();
            Console.Read();
        }
    }
    class Simple
    {
        Stopwatch sw = new Stopwatch();
        public void DoRun()
        {
            Console.WriteLine("Caller: Before call");
            ShowDealyAsync();
            Console.WriteLine("Caller: After call");
        }

        private async void ShowDealyAsync()
        {
            sw.Start();
            Console.WriteLine("  Before Delay: {0}",sw.ElapsedMilliseconds);
            await Task.Delay(5000);      //执行到await表达式时,立即返回到调用方法,等待5秒后执行后续部分
            Console.WriteLine(" After Delay : {0}",sw.ElapsedMilliseconds );//后续部分
        }
    }
}

猜你喜欢

转载自blog.csdn.net/ABC13222880223/article/details/85052247