QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 2301|回复: 0

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

[复制链接]

等级头衔

积分成就    金币 : 2861
   泡泡 : 1516
   精华 : 6
   在线时间 : 1328 小时
   最后登录 : 2026-5-15

丰功伟绩

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

联系方式
发表于 2023-6-26 20:00:45 | 显示全部楼层 |阅读模式
很多时候我们需要做一段延时处理,就直接Thread.Sleep(n)处理了,但实际上延时也可以用Task.Delay(n),那二者之间有没有区别呢?" Z# \3 h! e0 }- P0 z! o( C
我们先来看一个案例:
! U- q/ R6 [+ b# g
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();
        }
    }
}
运行结果:
- A  Q4 j% c: `; X 1.jpg
& D5 X3 W) g. W/ F7 v区别:* C2 ]) Y2 P7 ]2 G) o6 A8 L6 K7 z
①.Thread.Sleep()是同步延迟,既然是同步的,自然会阻塞当前线程;Task.Delay()是异步延迟,则不会阻塞线程;7 e! b. V7 M8 a+ _9 w) `
②.Thread.Sleep()不能中途取消,Task.Delay()可以,delay有四个重载方法,需要取消的话,可以调用Delay(int millisecondsDelay, CancellationToken cancellationToken)这个方法;) ]. {! `& B# U1 B
        //
        // 摘要:
        //     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);
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2026-5-29 00:23

Powered by paopaomj X3.5 © 2016-2025 sitemap

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