久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

C# Task.Delay() 和 Thread.Sleep() 區(qū)別

 ontheroad96j47 2021-11-08

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í)行過程中遇到await后就會返回執(zhí)行了,,待await的代碼執(zhí)行完畢后才繼續(xù)執(zhí)行接下來的代碼的,!

----------------------------------------------------------

Use Thread.Sleep when you want to block the current thread. 要阻止當(dāng)前線程時,請使用Thread.Sleep ,。

Use Task.Delay when you want a logical delay without blocking the current thread. 如果需要邏輯延遲而不阻塞當(dāng)前線程,,請使用Task.Delay

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 Thread.Sleep is far more accurate, ms accuracy is not really a problem, while Task.Delay can take 15-30ms minimal. 另外,有趣的是,, Thread.Sleep準(zhǔn)確性要高得多,,ms的準(zhǔn)確性并不是真正的問題,而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精度相比,,這兩個函數(shù)的開銷是最小的(如果您需要更精確的信息,請使用Stopwatch Class),。 Thread.Sleep still ties up your Thread, Task.Delay release it to do other work while you wait. Thread.Sleep仍然占用您的線程,, Task.Delay釋放它以便在您等待時進(jìn)行其他工作。

    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多