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

     很多时候我们需要做一段延时处理,就直接Thread.Sleep(n)处理了,但实际上延时也可以用Task.Delay(n),那二者之间有没有区别呢?

我们先来看一个案例:

using System;
using System.Threading;
using System.Threading.Tasks;


namespace ConsoleApp22
{
    class Program
    {
        static void Main(string[] args)
        {
            //Good writing
            Task.Run(async () =>
            {
                int delayTimeCount = 0;
                while (true)
                {
                    Console.WriteLine($"Delay第{++delayTimeCount}秒");
                    await Task.Delay(1000);
                }
            });


            //Bad writing
            Task.Run(() =>
            {
                int sleepTimeCount = 0;
                while (true)
                {
                    Console.WriteLine($"Thread{++sleepTimeCount}秒");
                    Thread.Sleep(1000);
                }
            });


            Console.ReadKey();
        }
    }
}

运行结果:

c19562019fea005137bdc34196e948b8.png

区别:

①.Thread.Sleep()是同步延迟,既然是同步的,自然会阻塞当前线程;Task.Delay()是异步延迟,则不会阻塞线程;
②.Thread.Sleep()不能中途取消,Task.Delay()可以,delay有四个重载方法,需要取消的话,可以调用Delay(int millisecondsDelay, CancellationToken cancellationToken)这个方法;

//
        // 摘要:
        //     Creates a task that completes after a specified number of milliseconds.
        //
        // 参数:
        //   millisecondsDelay:
        //     The number of milliseconds to wait before completing the returned task, or -1
        //     to wait indefinitely.
        //
        // 返回结果:
        //     A task that represents the time delay.
        //
        // 异常:
        //   T:System.ArgumentOutOfRangeException:
        //     The millisecondsDelay argument is less than -1.
        public static Task Delay(int millisecondsDelay);
        //
        // 摘要:
        //     Creates a cancellable task that completes after a specified number of milliseconds.
        //
        // 参数:
        //   millisecondsDelay:
        //     The number of milliseconds to wait before completing the returned task, or -1
        //     to wait indefinitely.
        //
        //   cancellationToken:
        //     A cancellation token to observe while waiting for the task to complete.
        //
        // 返回结果:
        //     A task that represents the time delay.
        //
        // 异常:
        //   T:System.ArgumentOutOfRangeException:
        //     The millisecondsDelay argument is less than -1.
        //
        //   T:System.Threading.Tasks.TaskCanceledException:
        //     The task has been canceled.
        //
        //   T:System.ObjectDisposedException:
        //     The provided cancellationToken has already been disposed.
        public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken);
        //
        // 摘要:
        //     Creates a task that completes after a specified time interval.
        //
        // 参数:
        //   delay:
        //     The time span to wait before completing the returned task, or TimeSpan.FromMilliseconds(-1)
        //     to wait indefinitely.
        //
        // 返回结果:
        //     A task that represents the time delay.
        //
        // 异常:
        //   T:System.ArgumentOutOfRangeException:
        //     delay represents a negative time interval other than TimeSpan.FromMilliseconds(-1).
        //     -or- The delay argument's System.TimeSpan.TotalMilliseconds property is greater
        //     than System.Int32.MaxValue.
        public static Task Delay(TimeSpan delay);
        //
        // 摘要:
        //     Creates a cancellable task that completes after a specified time interval.
        //
        // 参数:
        //   delay:
        //     The time span to wait before completing the returned task, or TimeSpan.FromMilliseconds(-1)
        //     to wait indefinitely.
        //
        //   cancellationToken:
        //     A cancellation token to observe while waiting for the task to complete.
        //
        // 返回结果:
        //     A task that represents the time delay.
        //
        // 异常:
        //   T:System.ArgumentOutOfRangeException:
        //     delay represents a negative time interval other than TimeSpan.FromMilliseconds(-1).
        //     -or- The delay argument's System.TimeSpan.TotalMilliseconds property is greater
        //     than System.Int32.MaxValue.
        //
        //   T:System.Threading.Tasks.TaskCanceledException:
        //     The task has been canceled.
        //
        //   T:System.ObjectDisposedException:
        //     The provided cancellationToken has already been disposed.
        public static Task Delay(TimeSpan delay, CancellationToken cancellationToken);

③在异步代码中通常使用await关键字调用Task.Delay(),而不是Thread.Sleep();

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、付费专栏及课程。

余额充值