QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

泡泡马甲APP 更多内容请下载泡泡马甲手机客户端APP 立即下载 ×
查看: 735|回复: 0

[C#] Task.Delay()和Thread.Sleep()有什么区别

[复制链接]

等级头衔

积分成就    金币 : 2806
   泡泡 : 1516
   精华 : 6
   在线时间 : 1244 小时
   最后登录 : 2024-5-5

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老

联系方式
发表于 2023-6-26 20:00:45 | 显示全部楼层 |阅读模式
很多时候我们需要做一段延时处理,就直接Thread.Sleep(n)处理了,但实际上延时也可以用Task.Delay(n),那二者之间有没有区别呢?
& Z6 P6 v( b/ h/ p$ N" P我们先来看一个案例:
- C$ Z/ o6 g+ @0 _1 X: z5 c: c/ S
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp22
  5. {
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             //Good writing
  11.             Task.Run(async () =>
  12.             {
  13.                 int delayTimeCount = 0;
  14.                 while (true)
  15.                 {
  16.                     Console.WriteLine($"Delay第{++delayTimeCount}秒");
  17.                     await Task.Delay(1000);
  18.                 }
  19.             });
  20.             //Bad writing
  21.             Task.Run(() =>
  22.             {
  23.                 int sleepTimeCount = 0;
  24.                 while (true)
  25.                 {
  26.                     Console.WriteLine($"Thread{++sleepTimeCount}秒");
  27.                     Thread.Sleep(1000);
  28.                 }
  29.             });
  30.             Console.ReadKey();
  31.         }
  32.     }
  33. }
运行结果:
; W# [9 N+ ?2 z- u. X3 A5 ^, A 1.jpg

) l, o0 r; u2 E" \区别:
3 M# |* q7 n1 j( l2 z1 g3 G①.Thread.Sleep()是同步延迟,既然是同步的,自然会阻塞当前线程;Task.Delay()是异步延迟,则不会阻塞线程;  Q+ J8 F" `% J7 i
②.Thread.Sleep()不能中途取消,Task.Delay()可以,delay有四个重载方法,需要取消的话,可以调用Delay(int millisecondsDelay, CancellationToken cancellationToken)这个方法;
4 l. J1 I+ K! J  S) h
  1.         //
  2.         // 摘要:
  3.         //     Creates a task that completes after a specified number of milliseconds.
  4.         //
  5.         // 参数:
  6.         //   millisecondsDelay:
  7.         //     The number of milliseconds to wait before completing the returned task, or -1
  8.         //     to wait indefinitely.
  9.         //
  10.         // 返回结果:
  11.         //     A task that represents the time delay.
  12.         //
  13.         // 异常:
  14.         //   T:System.ArgumentOutOfRangeException:
  15.         //     The millisecondsDelay argument is less than -1.
  16.         public static Task Delay(int millisecondsDelay);
  17.         //
  18.         // 摘要:
  19.         //     Creates a cancellable task that completes after a specified number of milliseconds.
  20.         //
  21.         // 参数:
  22.         //   millisecondsDelay:
  23.         //     The number of milliseconds to wait before completing the returned task, or -1
  24.         //     to wait indefinitely.
  25.         //
  26.         //   cancellationToken:
  27.         //     A cancellation token to observe while waiting for the task to complete.
  28.         //
  29.         // 返回结果:
  30.         //     A task that represents the time delay.
  31.         //
  32.         // 异常:
  33.         //   T:System.ArgumentOutOfRangeException:
  34.         //     The millisecondsDelay argument is less than -1.
  35.         //
  36.         //   T:System.Threading.Tasks.TaskCanceledException:
  37.         //     The task has been canceled.
  38.         //
  39.         //   T:System.ObjectDisposedException:
  40.         //     The provided cancellationToken has already been disposed.
  41.         public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken);
  42.         //
  43.         // 摘要:
  44.         //     Creates a task that completes after a specified time interval.
  45.         //
  46.         // 参数:
  47.         //   delay:
  48.         //     The time span to wait before completing the returned task, or TimeSpan.FromMilliseconds(-1)
  49.         //     to wait indefinitely.
  50.         //
  51.         // 返回结果:
  52.         //     A task that represents the time delay.
  53.         //
  54.         // 异常:
  55.         //   T:System.ArgumentOutOfRangeException:
  56.         //     delay represents a negative time interval other than TimeSpan.FromMilliseconds(-1).
  57.         //     -or- The delay argument's System.TimeSpan.TotalMilliseconds property is greater
  58.         //     than System.Int32.MaxValue.
  59.         public static Task Delay(TimeSpan delay);
  60.         //
  61.         // 摘要:
  62.         //     Creates a cancellable task that completes after a specified time interval.
  63.         //
  64.         // 参数:
  65.         //   delay:
  66.         //     The time span to wait before completing the returned task, or TimeSpan.FromMilliseconds(-1)
  67.         //     to wait indefinitely.
  68.         //
  69.         //   cancellationToken:
  70.         //     A cancellation token to observe while waiting for the task to complete.
  71.         //
  72.         // 返回结果:
  73.         //     A task that represents the time delay.
  74.         //
  75.         // 异常:
  76.         //   T:System.ArgumentOutOfRangeException:
  77.         //     delay represents a negative time interval other than TimeSpan.FromMilliseconds(-1).
  78.         //     -or- The delay argument's System.TimeSpan.TotalMilliseconds property is greater
  79.         //     than System.Int32.MaxValue.
  80.         //
  81.         //   T:System.Threading.Tasks.TaskCanceledException:
  82.         //     The task has been canceled.
  83.         //
  84.         //   T:System.ObjectDisposedException:
  85.         //     The provided cancellationToken has already been disposed.
  86.         public static Task Delay(TimeSpan delay, CancellationToken cancellationToken);
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号 )

GMT+8, 2024-5-7 12:31

Powered by paopaomj X3.4 © 2016-2024 sitemap

快速回复 返回顶部 返回列表