public:
 static System::Threading::Tasks::Task ^ Delay(int millisecondsDelay);
public static System.Threading.Tasks.Task Delay (int millisecondsDelay);
static member Delay : int -> System.Threading.Tasks.Task
Public Shared Function Delay (millisecondsDelay As Integer) As Task
// The example displays the following output: // Task t Status: RanToCompletion, Result: 42
open System.Threading.Tasks
let t =
    Task.Run<int>(fun () ->
        task {
            do! Task.Delay 1000
            return 42
t.Wait()
printfn $"Task t Status: {t.Status}, Result: {t.Result}"
// The example displays the following output:
//        Task t Status: RanToCompletion, Result: 42
Imports System.Threading.Tasks
Module Example
   Public Sub Main()
      Dim t = Task.Run(Async Function()
                                Await Task.Delay(1000)
                                Return 42
                       End Function)
      t.Wait()
      Console.WriteLine("Task t Status: {0}, Result: {1}",
                        t.Status, t.Result)
   End Sub
End Module
' The example displays the following output:
'       Task t Status: RanToCompletion, Result: 42
              Delay 方法通常用于延迟指定时间间隔内任务的全部或部分操作。 最常见的是引入时间延迟:

  • 在任务的开头,如以下示例所示。

    Stopwatch sw = Stopwatch.StartNew();
    var delay = Task.Delay(1000).ContinueWith(_ =>
                               { sw.Stop();
                                 return sw.ElapsedMilliseconds; } );
    Console.WriteLine("Elapsed milliseconds: {0}", delay.Result);
    // The example displays output like the following:
    //        Elapsed milliseconds: 1013
    
        let sw = Stopwatch.StartNew()
        let delay =
                .Delay(1000)
                .ContinueWith(fun _ ->
                    sw.Stop()
                    sw.ElapsedMilliseconds)
        printfn $"Elapsed milliseconds: {delay.Result}"
    // The example displays output like the following:
    //        Elapsed milliseconds: 1013
    
    Dim sw As Stopwatch = Stopwatch.StartNew()
    Dim delay1 = Task.Delay(1000)
    Dim delay2 = delay1.ContinueWith( Function(antecedent)
                            sw.Stop()
                            Return sw.ElapsedMilliseconds
                          End Function)
    Console.WriteLine("Elapsed milliseconds: {0}", delay2.Result)
    ' The example displays output like the following:
    '        Elapsed milliseconds: 1013
    
  • 任务正在执行时。 在这种情况下,对 Delay 方法的调用在任务中作为子任务执行,如以下示例所示。 请注意,由于调用 Delay 方法的任务以异步方式执行,因此父任务必须等待它使用 await 关键字完成。

    var delay = Task.Run( async () => { Stopwatch sw = Stopwatch.StartNew();
                                        await Task.Delay(2500);
                                        sw.Stop();
                                        return sw.ElapsedMilliseconds; });
    Console.WriteLine("Elapsed milliseconds: {0}", delay.Result);
    // The example displays output like the following:
    //        Elapsed milliseconds: 2501
    
        let delay =
            Task.Run<int64>(fun () ->
                task {
                    let sw = Stopwatch.StartNew()
                    do! Task.Delay 2500
                    sw.Stop()
                    return sw.ElapsedMilliseconds
        printfn $"Elapsed milliseconds: {delay.Result}"
    // The example displays output like the following:
    //        Elapsed milliseconds: 2501
    
    Dim delay = Task.Run( Async Function()
                             Dim sw As Stopwatch = Stopwatch.StartNew()
                             Await Task.Delay(2500)
                             sw.Stop()
                             Return sw.ElapsedMilliseconds
                          End Function )
    Console.WriteLine("Elapsed milliseconds: {0}", delay.Result)
    ' The example displays output like the following:
    '        Elapsed milliseconds: 2501
    

    在指定的时间延迟后,任务将处于 RanToCompletion 状态完成。

    此方法取决于系统时钟。 这意味着,如果 millisecondsDelay 参数小于系统时钟的分辨率,则时间延迟大约等于系统时钟的分辨率,而 Windows 系统上的分辨率约为 15 毫秒。

    所使用的系统时钟与 GetTickCount使用的时钟相同,这不受 timeBeginPeriodtimeEndPeriod所做的更改的影响。

    public:
     static System::Threading::Tasks::Task ^ Delay(TimeSpan delay);
    public static System.Threading.Tasks.Task Delay (TimeSpan delay);
    static member Delay : TimeSpan -> System.Threading.Tasks.Task
    Public Shared Function Delay (delay As TimeSpan) As Task
    // The example displays the following output: // Task t Status: RanToCompletion, Result: 42
    open System
    open System.Threading.Tasks
    let t =
        Task.Run<int>(fun () ->
            task {
                do! Task.Delay(TimeSpan.FromSeconds 1.5)
                return 42
    t.Wait()
    printfn $"Task t Status: {t.Status}, Result: {t.Result}"
    // The example displays the following output:
    //        Task t Status: RanToCompletion, Result: 42
    
    Imports System.Threading.Tasks
    Module Example
       Public Sub Main()
          Dim t = Task.Run(Async Function()
                                    Await Task.Delay(TimeSpan.FromSeconds(1.5))
                                    Return 42
                           End Function)
          t.Wait()
          Console.WriteLine("Task t Status: {0}, Result: {1}",
                            t.Status, t.Result)
       End Sub
    End Module
    ' The example displays the following output:
    '       Task t Status: RanToCompletion, Result: 42
        	

    在指定的时间延迟后,任务以 RanToCompletion 状态完成。

    有关使用方案和其他示例,请参阅 Delay(Int32) 重载的文档。

    此方法取决于系统时钟。 这意味着,如果 delay 参数小于系统时钟的分辨率,则时间延迟大约等于系统时钟的分辨率,而 Windows 系统上的分辨率约为 15 毫秒。

    所使用的系统时钟与 GetTickCount使用的时钟相同,这不受 timeBeginPeriodtimeEndPeriod所做的更改的影响。

    public:
     static System::Threading::Tasks::Task ^ Delay(int millisecondsDelay, System::Threading::CancellationToken cancellationToken);
    public static System.Threading.Tasks.Task Delay (int millisecondsDelay, System.Threading.CancellationToken cancellationToken);
    static member Delay : int * System.Threading.CancellationToken -> System.Threading.Tasks.Task
    Public Shared Function Delay (millisecondsDelay As Integer, cancellationToken As CancellationToken) As Task

    以下示例启动一个任务,该任务包含对 Delay(Int32, CancellationToken) 方法的调用,但延迟为 1 秒。 在延迟间隔过前,令牌将被取消。 该示例的输出显示,因此会引发 TaskCanceledException,并将任务的 Status 属性设置为 Canceled

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    public class Example
       public static void Main()
          CancellationTokenSource source = new CancellationTokenSource();
          var t = Task.Run(async delegate
                     await Task.Delay(1000, source.Token);
                     return 42;
          source.Cancel();
          try {
             t.Wait();
          catch (AggregateException ae) {
             foreach (var e in ae.InnerExceptions)
                Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
          Console.Write("Task t Status: {0}", t.Status);
          if (t.Status == TaskStatus.RanToCompletion)
             Console.Write(", Result: {0}", t.Result);
          source.Dispose();
    // The example displays the following output:
    //       TaskCanceledException: A task was canceled.
    //       Task t Status: Canceled
    
    open System
    open System.Threading
    open System.Threading.Tasks
    let source = new CancellationTokenSource()
    let t =
        Task.Run<int>(fun () ->
            task {
                do! Task.Delay(1000, source.Token)
                return 42
    source.Cancel()
        t.Wait()
    with :? AggregateException as ae ->
        for e in ae.InnerExceptions do
            printfn $"{e.GetType().Name}: {e.Message}"
    printf $"Task t Status: {t.Status}"
    if t.Status = TaskStatus.RanToCompletion then
        printf $", Result: {t.Result}"
    source.Dispose()
    // The example displays the following output:
    //       TaskCanceledException: A task was canceled.
    //       Task t Status: Canceled
    
    Imports System.Threading
    Imports System.Threading.Tasks
    Module Example
       Public Sub Main()
          Dim source As New CancellationTokenSource()
          Dim t = Task.Run(Async Function()
                                    Await Task.Delay(1000, source.Token)
                                    Return 42
                           End Function)
          source.Cancel()
             t.Wait()
          Catch ae As AggregateException
             For Each e In ae.InnerExceptions
                Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message)
          End Try
          Console.Write("Task t Status: {0}", t.Status)
          If t.Status = TaskStatus.RanToCompletion Then
             Console.Write(", Result: {0}", t.Result)
          End If
          source.Dispose()
       End Sub
    End Module
    ' The example displays the following output:
    '       TaskCanceledException: A task was canceled.
    '       Task t Status: Canceled
        	

    如果在指定的时间延迟之前发出取消令牌的信号,则 TaskCanceledException 异常结果,并且任务在 Canceled 状态下完成。 否则,任务在指定的时间延迟过后处于 RanToCompletion 状态完成。

    有关使用方案和其他示例,请参阅 Delay(Int32) 重载的文档。

    此方法取决于系统时钟。 这意味着,如果 millisecondsDelay 参数小于系统时钟的分辨率,则时间延迟大约等于系统时钟的分辨率,而 Windows 系统上的分辨率约为 15 毫秒。

    所使用的系统时钟与 GetTickCount使用的时钟相同,这不受 timeBeginPeriodtimeEndPeriod所做的更改的影响。

    public:
     static System::Threading::Tasks::Task ^ Delay(TimeSpan delay, System::Threading::CancellationToken cancellationToken);
    public static System.Threading.Tasks.Task Delay (TimeSpan delay, System.Threading.CancellationToken cancellationToken);
    static member Delay : TimeSpan * System.Threading.CancellationToken -> System.Threading.Tasks.Task
    Public Shared Function Delay (delay As TimeSpan, cancellationToken As CancellationToken) As Task

    以下示例启动一个任务,该任务包含对 Delay(TimeSpan, CancellationToken) 方法的调用,延迟为 1.5 秒。 在延迟间隔过前,令牌将被取消。 该示例的输出显示,因此会引发 TaskCanceledException,并将任务的 Status 属性设置为 Canceled

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    public class Example
       public static void Main()
          CancellationTokenSource source = new CancellationTokenSource();
          var t = Task.Run(async delegate
                     await Task.Delay(TimeSpan.FromSeconds(1.5), source.Token);
                     return 42;
          source.Cancel();
          try {
             t.Wait();
          catch (AggregateException ae) {
             foreach (var e in ae.InnerExceptions)
                Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
          Console.Write("Task t Status: {0}", t.Status);
          if (t.Status == TaskStatus.RanToCompletion)
             Console.Write(", Result: {0}", t.Result);
          source.Dispose();
    // The example displays output like the following:
    //       TaskCanceledException: A task was canceled.
    //       Task t Status: Canceled
    
    open System
    open System.Threading
    open System.Threading.Tasks
    let source = new CancellationTokenSource()
    let t =
        Task.Run<int>(fun () ->
            task {
                do! Task.Delay(TimeSpan.FromSeconds(1.5), source.Token)
                return 42
    source.Cancel()
        t.Wait()
    with :? AggregateException as ae ->
        for e in ae.InnerExceptions do
            printfn $"{e.GetType().Name}: {e.Message}"
    printf $"Task t Status: {t.Status}"
    if t.Status = TaskStatus.RanToCompletion then
        printf $", Result: {t.Result}"
    source.Dispose()
    // The example displays output like the following:
    //       TaskCanceledException: A task was canceled.
    //       Task t Status: Canceled
    
    Imports System.Threading
    Imports System.Threading.Tasks
    Module Example
       Public Sub Main()
          Dim source As New CancellationTokenSource()
          Dim t = Task.Run(Async Function()
                                    Await Task.Delay(TimeSpan.FromSeconds(1.5),
                                                     source.Token)
                                    Return 42
                           End Function)
          source.Cancel()
             t.Wait()
          Catch ae As AggregateException
             For Each e In ae.InnerExceptions
                Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message)
          End Try
          Console.Write("Task t Status: {0}", t.Status)
          If t.Status = TaskStatus.RanToCompletion Then
             Console.Write(", Result: {0}", t.Result)
          End If
          source.Dispose()
       End Sub
    End Module
    ' The example displays output like the following:
    '       TaskCanceledException: A task was canceled.
    '       Task t Status: Canceled
    

    请注意,此示例包含潜在的争用条件:它取决于在取消令牌时异步执行延迟的任务。 尽管从调用到 Delay(TimeSpan, CancellationToken) 方法的 1.5 秒延迟可能会做出这种假设,但是,在取消令牌之前,对 Delay(TimeSpan, CancellationToken) 方法的调用可能会返回。 在这种情况下,该示例生成以下输出:

    Task t Status: RanToCompletion, Result: 42
        	

    如果在指定的时间延迟之前发出取消令牌的信号,则 TaskCanceledException 异常结果,并且任务在 Canceled 状态下完成。 否则,任务在指定的时间延迟过后处于 RanToCompletion 状态完成。

    有关使用方案和其他示例,请参阅 Delay(Int32) 重载的文档。

    此方法取决于系统时钟。 这意味着,如果 delay 参数小于系统时钟的分辨率,则时间延迟大约等于系统时钟的分辨率,而 Windows 系统上的分辨率约为 15 毫秒。

    所使用的系统时钟与 GetTickCount使用的时钟相同,这不受 timeBeginPeriodtimeEndPeriod所做的更改的影响。

    public:
     static System::Threading::Tasks::Task ^ Delay(TimeSpan delay, TimeProvider ^ timeProvider);
    public static System.Threading.Tasks.Task Delay (TimeSpan delay, TimeProvider timeProvider);
    static member Delay : TimeSpan * TimeProvider -> System.Threading.Tasks.Task
    Public Shared Function Delay (delay As TimeSpan, timeProvider As TimeProvider) As Task
    public:
     static System::Threading::Tasks::Task ^ Delay(TimeSpan delay, TimeProvider ^ timeProvider, System::Threading::CancellationToken cancellationToken);
    public static System.Threading.Tasks.Task Delay (TimeSpan delay, TimeProvider timeProvider, System.Threading.CancellationToken cancellationToken);
    static member Delay : TimeSpan * TimeProvider * System.Threading.CancellationToken -> System.Threading.Tasks.Task
    Public Shared Function Delay (delay As TimeSpan, timeProvider As TimeProvider, cancellationToken As CancellationToken) As Task
  •