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 *******"); } } }
运行结果: 我们可以看到这个代码的执行过程中遇到 Use Use 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 |
|
来自: ontheroad96j47 > 《待分类》