1、Thread.Sleep 是同步延遲,,Task.Delay異步延遲,。 2、Thread.Sleep 會阻塞線程,,Task.Delay不會,。 3、Thread.Sleep不能取消,,Task.Delay可以,。 4. Task.Delay() 比 Thread.Sleep() 消耗更多的資源,但是Task.Delay()可用于為方法返回Task類型,;或者根據(jù)CancellationToken取消標(biāo)記動態(tài)取消等待 5. Task.Delay() 實(shí)質(zhì)創(chuàng)建一個運(yùn)行給定時間的任務(wù),, Thread.Sleep() 使當(dāng)前線程休眠給定時間。 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 *******"); } } }
運(yùn)行結(jié)果: 我們可以看到這個代碼的執(zhí)行過程中遇到 Use Use Efficiency should not be a paramount concern with these methods. 對于這些方法,,效率不應(yīng)該是最重要的問題,。 Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds. 它們在現(xiàn)實(shí)世界中的主要用途是作為I / O操作的重試計(jì)時器,,其數(shù)量級為秒而不是毫秒 Also, it is interesting to notice that |
|