Task.Delay
è implementato come segue:
public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken)
{
//error checking
Task.DelayPromise delayPromise = new Task.DelayPromise(cancellationToken);
if (cancellationToken.CanBeCanceled)
delayPromise.Registration = cancellationToken.InternalRegisterWithoutEC((Action<object>) (state => ((Task.DelayPromise) state).Complete()), (object) delayPromise);
if (millisecondsDelay != -1)
{
delayPromise.Timer = new Timer((TimerCallback) (state => ((Task.DelayPromise) state).Complete()), (object) delayPromise, millisecondsDelay, -1);
delayPromise.Timer.KeepRootedWhileScheduled();
}
return (Task) delayPromise;
}
utilizza sicuramente timer. Sono utilizzati in una classe chiamata DelayPromise
. Ecco l'implementazione per questo:
private sealed class DelayPromise : Task<VoidTaskResult>
{
internal readonly CancellationToken Token;
internal CancellationTokenRegistration Registration;
internal Timer Timer;
internal DelayPromise(CancellationToken token)
{
this.Token = token;
}
internal void Complete()
{
if (!(this.Token.IsCancellationRequested ? this.TrySetCanceled(this.Token) : this.TrySetResult(new VoidTaskResult())))
return;
if (this.Timer != null)
this.Timer.Dispose();
this.Registration.Dispose();
}
}
Utilizza un timer, ma non mi sembra una preoccupazione. Il timer richiama semplicemente il metodo completo, e ciò che fa è controllare se è stato cancellato, in tal caso cancellarlo, altrimenti solo restituire un risultato. Mi sembra soddisfacente.
fonte
2013-06-29 09:58:25
@ColeJohnson Perché 'Thread.Sleep' non è' async'? –
E Task.Delay è? Non ha senso. Se voglio ritardare un thread, lo voglio ADESSO, non generare un altro thread per dire a uno di fermarsi. –
@Cole Il punto è fare in modo che un thread attenda un po 'di tempo prima di riprendere. Il punto non è ritardare un thread. –