Task.Delay 方法

定义

创建将在时间延迟后完成的任务。Creates a task that will complete after a time delay.

重载

Delay(Int32, CancellationToken)

创建一个在指定的毫秒数后完成的可取消任务。Creates a cancellable task that completes after a specified number of milliseconds.

Delay(TimeSpan, CancellationToken)

创建一个在指定的时间间隔后完成的可取消任务。Creates a cancellable task that completes after a specified time interval.

Delay(Int32)

创建一个在指定的毫秒数后完成的任务。Creates a task that completes after a specified number of milliseconds.

Delay(TimeSpan)

创建一个在指定的时间间隔后完成的任务。Creates a task that completes after a specified time interval.

Delay(Int32, CancellationToken)

创建一个在指定的毫秒数后完成的可取消任务。Creates a cancellable task that completes after a specified number of milliseconds.

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

参数

millisecondsDelay
Int32

在完成返回的任务前要等待的毫秒数;如果无限期等待,则为 -1。The number of milliseconds to wait before completing the returned task, or -1 to wait indefinitely.

cancellationToken
CancellationToken

等待任务完成期间要观察的取消标记。A cancellation token to observe while waiting for the task to complete.

返回

Task

表示时间延迟的任务。A task that represents the time delay.

例外

millisecondsDelay 参数小于 -1。The millisecondsDelay argument is less than -1.

该任务已取消。The task has been canceled.

已释放提供的 cancellationTokenThe provided cancellationToken has already been disposed.

示例

下面的示例启动一个任务,该任务包括对方法的调用 Delay(Int32, CancellationToken) ,且延迟为一秒。The following example launches a task that includes a call to the Delay(Int32, CancellationToken) method with a one second delay. 在延迟间隔结束之前,会取消标记。Before the delay interval elapses, the token is cancelled. 该示例的输出显示,引发了, TaskCanceledException 并将 tasks 的 Status 属性设置为 CanceledThe output from the example shows that, as a result, a TaskCanceledException is thrown, and the tasks' Status property is set to 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
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()
      Try
         t.Wait()
      Catch ae As AggregateException
         For Each e In ae.InnerExceptions
            Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message)
         Next
      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 生成异常结果,并且任务在状态中完成 CanceledIf the cancellation token is signaled before the specified time delay, a TaskCanceledException exception results, and the task is completed in the Canceled state. 否则,在 RanToCompletion 指定的时间延迟结束后,任务将以状态完成。Otherwise, the task is completed in the RanToCompletion state once the specified time delay has elapsed.

有关使用方案和其他示例,请参阅重载的文档 Delay(Int32)For usage scenarios and additional examples, see the documentation for the Delay(Int32) overload.

此方法取决于系统时钟。This method depends on the system clock. 这意味着,如果 millisecondsDelay 参数小于系统时钟的分辨率(在 Windows 系统上约为15毫秒),则时间延迟约等于系统时钟的分辨率。This means that the time delay will approximately equal the resolution of the system clock if the millisecondsDelay argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems.

适用于

Delay(TimeSpan, CancellationToken)

创建一个在指定的时间间隔后完成的可取消任务。Creates a cancellable task that completes after a specified time interval.

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

在完成返回的任务前等待的时间跨度;如果无限期等待,则为 TimeSpan.FromMilliseconds(-1)The time span to wait before completing the returned task, or TimeSpan.FromMilliseconds(-1) to wait indefinitely.

cancellationToken
CancellationToken

等待任务完成期间要观察的取消标记。A cancellation token to observe while waiting for the task to complete.

返回

Task

表示时间延迟的任务。A task that represents the time delay.

例外

delay 表示除 TimeSpan.FromMilliseconds(-1) 以外的负时间间隔。delay represents a negative time interval other than TimeSpan.FromMilliseconds(-1).

- 或 --or- delay 参数的 TotalMilliseconds 属性大于 MaxValueThe delay argument's TotalMilliseconds property is greater than MaxValue.

该任务已取消。The task has been canceled.

已释放提供的 cancellationTokenThe provided cancellationToken has already been disposed.

示例

下面的示例启动一个任务,其中包括对方法的调用 Delay(TimeSpan, CancellationToken) ,但延迟为1.5 秒。The following example launches a task that includes a call to the Delay(TimeSpan, CancellationToken) method with a 1.5 second delay. 在延迟间隔结束之前,会取消标记。Before the delay interval elapses, the token is cancelled. 该示例的输出显示,引发了, TaskCanceledException 并将 tasks 的 Status 属性设置为 CanceledThe output from the example shows that, as a result, a TaskCanceledException is thrown, and the tasks' Status property is set to 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
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()
      Try
         t.Wait()
      Catch ae As AggregateException
         For Each e In ae.InnerExceptions
            Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message)
         Next
      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

请注意,此示例包含潜在的争用条件:在取消标记时,它依赖于异步执行延迟的任务。Note that this example includes a potential race condition: it depends on the task asynchronously executing the delay when the token is cancelled. 尽管对方法的调用中,1.5 秒的延迟 Delay(TimeSpan, CancellationToken) 会使该假设成为可能,但是,在取消标记之前,对方法的调用可能会 Delay(TimeSpan, CancellationToken) 返回。Although the 1.5 second delay from the call to the Delay(TimeSpan, CancellationToken) method makes that assumption likely, it is nevertheless possible that the call to the Delay(TimeSpan, CancellationToken) method could return before the token is cancelled. 在这种情况下,该示例生成以下输出:In that case, the example produces the following output:

Task t Status: RanToCompletion, Result: 42  

注解

如果在指定的时间延迟之前向取消标记发出信号,则会 TaskCanceledException 生成异常结果,并且任务在状态中完成 CanceledIf the cancellation token is signaled before the specified time delay, a TaskCanceledException exception results, and the task is completed in the Canceled state. 否则,在 RanToCompletion 指定的时间延迟结束后,任务将以状态完成。Otherwise, the task is completed in the RanToCompletion state once the specified time delay has elapsed.

有关使用方案和其他示例,请参阅重载的文档 Delay(Int32)For usage scenarios and additional examples, see the documentation for the Delay(Int32) overload.

此方法取决于系统时钟。This method depends on the system clock. 这意味着,如果 delay 参数小于系统时钟的分辨率(在 Windows 系统上约为15毫秒),则时间延迟约等于系统时钟的分辨率。This means that the time delay will approximately equal the resolution of the system clock if the delay argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems.

适用于

Delay(Int32)

创建一个在指定的毫秒数后完成的任务。Creates a task that completes after a specified number of milliseconds.

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

参数

millisecondsDelay
Int32

在完成返回的任务前要等待的毫秒数;如果无限期等待,则为 -1。The number of milliseconds to wait before completing the returned task, or -1 to wait indefinitely.

返回

Task

表示时间延迟的任务。A task that represents the time delay.

例外

millisecondsDelay 参数小于 -1。The millisecondsDelay argument is less than -1.

示例

下面的示例演示方法的简单用法 DelayThe following example shows a simple use of the Delay method.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var t = Task.Run(async delegate
              {
                 await Task.Delay(1000);
                 return 42;
              });
      t.Wait();
      Console.WriteLine("Task t Status: {0}, Result: {1}",
                        t.Status, 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方法通常用于在指定的时间间隔内延迟任务的全部或部分操作。The Delay method is typically used to delay the operation of all or part of a task for a specified time interval. 最常见的情况是,会引入时间延迟:Most commonly, the time delay is introduced:

  • 在任务开始时,如下面的示例所示。At the beginning of the task, as the following example shows.

    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
    
    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
    
  • 在任务执行期间的某个时间段。Sometime while the task is executing. 在这种情况下,对方法的调用 Delay 作为任务内的子任务执行,如下面的示例所示。In this case, the call to the Delay method executes as a child task within a task, as the following example shows. 请注意,调用方法的任务是 Delay 异步执行的,父任务必须等待它完成,方法是使用 await 关键字。Note that since the task that calls the Delay method executes asynchronously, the parent task must wait for it to complete by using the await keyword.

    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
    
    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
    

在指定的时间延迟后,任务在状态下完成 RanToCompletionAfter the specified time delay, the task is completed in the RanToCompletion state.

此方法取决于系统时钟。This method depends on the system clock. 这意味着,如果 millisecondsDelay 参数小于系统时钟的分辨率(在 Windows 系统上约为15毫秒),则时间延迟约等于系统时钟的分辨率。This means that the time delay will approximately equal the resolution of the system clock if the millisecondsDelay argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems.

适用于

Delay(TimeSpan)

创建一个在指定的时间间隔后完成的任务。Creates a task that completes after a specified time interval.

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

参数

delay
TimeSpan

在完成返回的任务前等待的时间跨度;如果无限期等待,则为 TimeSpan.FromMilliseconds(-1)The time span to wait before completing the returned task, or TimeSpan.FromMilliseconds(-1) to wait indefinitely.

返回

Task

表示时间延迟的任务。A task that represents the time delay.

例外

delay 表示除 TimeSpan.FromMilliseconds(-1) 以外的负时间间隔。delay represents a negative time interval other than TimeSpan.FromMilliseconds(-1).

- 或 --or- delay 参数的 TotalMilliseconds 属性大于 MaxValueThe delay argument's TotalMilliseconds property is greater than MaxValue.

示例

下面的示例演示方法的简单用法 DelayThe following example shows a simple use of the Delay method.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var t = Task.Run(async delegate
              {
                 await Task.Delay(TimeSpan.FromSeconds(1.5));
                 return 42;
              });
      t.Wait();
      Console.WriteLine("Task t Status: {0}, Result: {1}",
                        t.Status, 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 状态完成。After the specified time delay, the task is completed in RanToCompletion state.

有关使用方案和其他示例,请参阅重载的文档 Delay(Int32)For usage scenarios and additional examples, see the documentation for the Delay(Int32) overload.

此方法取决于系统时钟。This method depends on the system clock. 这意味着,如果 delay 参数小于系统时钟的分辨率(在 Windows 系统上约为15毫秒),则时间延迟约等于系统时钟的分辨率。This means that the time delay will approximately equal the resolution of the system clock if the delay argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems.

适用于