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.

提供的 cancellationToken 已經過處置。The 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.

提供的 cancellationToken 已經過處置。The 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 以非同步方式執行,所以父工作必須使用關鍵字等候它完成 awaitNote 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.

適用於