Thread.Sleep vs Task.Delay?

Roy*_*mir 54 c# multithreading .net-4.0 .net-4.5

我知道Thread.Sleep阻止线程.

Task.Delay也阻止?或者它就像是Timer使用一个线程进行所有回调(当不重叠时)?

(这个问题不包括差异)

Kev*_*sse 54

MSDN上的文档令人失望,但Task.Delay使用Reflector进行反编译可提供更多信息:

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;
}
Run Code Online (Sandbox Code Playgroud)

基本上,这个方法只是一个包含在任务内部的计时器.所以是的,你可以说它就像计时器一样.

  • 可以将"等待Task.Delay(1000)"视为Thread.Sleep(1000)的异步版本,因为它不会阻止.当我需要等待但不想阻止UI或吃掉线程时,我在GUI工具中使用它. (12认同)