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 *******");
        }
    }
}

运行结果:

c6169a96c3dd967a5a178ec172d86464.png

我们可以看到这个代码的执行过程中遇到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释放它以便在您等待时进行其他工作。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的Thread.Sleep()方法用于使线程挂起一段时间。它的作用是让当前线程暂停执行一段时间,以便给其他线程或进程使用CPU资源的机会。\[1\]当调用Thread.Sleep(1000)时,表示当前线程会被挂起1秒钟,然后再继续执行。\[1\]如果调用Thread.Sleep(0),则表示当前线程会暂时放弃CPU,让其他已经准备好运行的、具有同等优先级的线程有机会执行。\[2\]\[3\]这个方法的作用是让当前线程让位,释放一些未用的时间片给其他线程或进程使用。 #### 引用[.reference_title] - *1* [C# 理解Thread.Sleep()方法](https://blog.csdn.net/yjpfinui/article/details/121669983)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [C# 延迟Task.Delay()和Thread.Sleep() 学习](https://blog.csdn.net/weixin_42009898/article/details/118912633)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [解决C#Thread.Sleep()的作用及用法](https://blog.csdn.net/mgtts/article/details/83740123)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值