Thread.Sleep(1000) 、Task.Delay(1000).Wait() 区别

1、文章:https://code.msdn.microsoft.com/ThreadSleep-vs-TaskDelay-766b46b7

2、Thread.Sleep 是同步延迟。 Task.Delay异步延迟。

3、Thread.Sleep 会阻塞线程,Task.Delay不会。

4、Thread.Sleep不能取消,Task.Delay可以。

5、反编译Task.Delay,基本上讲它就是个包裹在任务中的定时器。

 

 
  1. public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken)

  2. {

  3. if (millisecondsDelay < -1)

  4. {

  5. throw new ArgumentOutOfRangeException("millisecondsDelay", Environment.GetResourceString("Task_Delay_InvalidMillisecondsDelay"));

  6. }

  7. if (cancellationToken.IsCancellationRequested)

  8. {

  9. return FromCancellation(cancellationToken);

  10. }

  11. if (millisecondsDelay == 0)

  12. {

  13. return CompletedTask;

  14. }

  15. DelayPromise state = new DelayPromise(cancellationToken);

  16. if (cancellationToken.CanBeCanceled)

  17. {

  18. state.Registration = cancellationToken.InternalRegisterWithoutEC(delegate (object state) {

  19. ((DelayPromise) state).Complete();

  20. }, state);

  21. }

  22. if (millisecondsDelay != -1)

  23. {

  24. state.Timer = new Timer(delegate (object state) {

  25. ((DelayPromise) state).Complete();

  26. }, state, millisecondsDelay, -1);

  27. state.Timer.KeepRootedWhileScheduled();

  28. }

  29. return state;

  30. }

 

 

 

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 );//后续部分        }    }}
--------------------- 
作者:abc13222880223 
来源:CSDN 
原文:https://blog.csdn.net/ABC13222880223/article/details/85052247 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值