C# Task.Delay() 和 Thread.Sleep() 区别

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

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

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

4. Task.Delay() 比 Thread.Sleep() 消耗更多的资源,但是Task.Delay()可用于为方法返回Task类型;或者根据CancellationToken取消标记动态取消等待

5. Task.Delay() 实质创建一个运行给定时间的任务, Thread.Sleep() 使当前线程休眠给定时间。

using System;using System.Diagnostics;using System.Threading;using System.Threading.Tasks;
namespace ConsoleApp5{    class Program    {        static void Main(string[] args)
        {            Task delay = asyncTask();            syncCode();            delay.Wait();            Console.ReadLine();        }        static async Task asyncTask()        {            var sw = new Stopwatch();            sw.Start();            Console.WriteLine("async: Starting *");            Task delay = Task.Delay(5000);            Console.WriteLine("async: Running for {0} seconds **", sw.Elapsed.TotalSeconds);            await delay;            Console.WriteLine("async: Running for {0} seconds ***", sw.Elapsed.TotalSeconds);            Console.WriteLine("async: Done ****");        }        static void syncCode()        {            var sw = new Stopwatch();            sw.Start();            Console.WriteLine("sync: Starting *****");            Thread.Sleep(5000);            Console.WriteLine("sync: Running for {0} seconds ******", sw.Elapsed.TotalSeconds);            Console.WriteLine("sync: Done *******");        }    }}

运行结果:

C# Task.Delay() 和 Thread.Sleep() 区别

我们可以看到这个代码的执行过程中遇到await后就会返回执行了,待await的代码执行完毕后才继续执行接下来的代码的!

----------------------------------------------------------

Use Thread.Sleep when you want to block the current thread. 要阻止当前线程时,请使用Thread.Sleep 。

Use Task.Delay when you want a logical delay without blocking the current thread. 如果需要逻辑延迟而不阻塞当前线程,请使用Task.Delay 。

Efficiency should not be a paramount concern with these methods. 对于这些方法,效率不应该是最重要的问题。 Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds. 它们在现实世界中的主要用途是作为I / O操作的重试计时器,其数量级为秒而不是毫秒

Also, it is interesting to notice that Thread.Sleep is far more accurate, ms accuracy is not really a problem, while Task.Delay can take 15-30ms minimal. 另外,有趣的是, Thread.Sleep准确性要高得多,ms的准确性并不是真正的问题,而Task.Delay占用时间最少为15-30ms。 The overhead on both functions is minimal compared to the ms accuracy they have (use Stopwatch Class if you need something more accurate). 与它们具有的ms精度相比,这两个函数的开销是最小的(如果您需要更精确的信息,请使用Stopwatch Class)。 Thread.Sleep still ties up your Thread, Task.Delay release it to do other work while you wait. Thread.Sleep仍然占用您的线程, Task.Delay释放它以便在您等待时进行其他工作。