13
11/2015
Thread.Sleep(1000) 、Task.Delay(1000).Wait() 区别(转)
1、文章:https://code.msdn.microsoft.com/ThreadSleep-vs-TaskDelay-766b46b7
2、Thread.Sleep 是同步延迟。 Task.Delay异步延迟。
3、Thread.Sleep 会阻塞线程,Task.Delay不会。
4、Thread.Sleep不能取消,Task.Delay可以。
5、反编译Task.Delay,基本上讲它就是个包裹在任务中的定时器。
public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken) { if (millisecondsDelay < -1) { throw new ArgumentOutOfRangeException("millisecondsDelay", Environment.GetResourceString("Task_Delay_InvalidMillisecondsDelay")); } if (cancellationToken.IsCancellationRequested) { return FromCancellation(cancellationToken); } if (millisecondsDelay == 0) { return CompletedTask; } DelayPromise state = new DelayPromise(cancellationToken); if (cancellationToken.CanBeCanceled) { state.Registration = cancellationToken.InternalRegisterWithoutEC(delegate (object state) { ((DelayPromise) state).Complete(); }, state); } if (millisecondsDelay != -1) { state.Timer = new Timer(delegate (object state) { ((DelayPromise) state).Complete(); }, state, millisecondsDelay, -1); state.Timer.KeepRootedWhileScheduled(); } return state; }
0 条评论