Прочетете на английски Редактиране

Споделяне чрез


Task.Delay Method

Definition

Creates a task that will complete after a time delay.

Overloads

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.

Delay(TimeSpan, CancellationToken)

Creates a cancellable task that completes after a specified time interval.

Delay(TimeSpan, TimeProvider)

Creates a task that completes after a specified time interval.

Delay(TimeSpan, TimeProvider, CancellationToken)

Creates a cancellable task that completes after a specified time interval.

Delay(Int32)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a task that completes after a specified number of milliseconds.

public static System.Threading.Tasks.Task Delay (int millisecondsDelay);

Parameters

millisecondsDelay
Int32

The number of milliseconds to wait before completing the returned task, or -1 to wait indefinitely.

Returns

A task that represents the time delay.

Exceptions

The millisecondsDelay argument is less than -1.

Examples

The 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

Remarks

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
    
  • Sometime while the task is executing. In this case, the call to the Delay method executes as a child task within a task, as the following example shows. 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
    

After the specified time delay, the task is completed in the RanToCompletion state.

This method depends on the system clock. 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.

Бележка

The system clock that is used is the same clock used by GetTickCount, which is not affected by changes made with timeBeginPeriod and timeEndPeriod.

Applies to

.NET 9 и други версии
Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Delay(TimeSpan)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a task that completes after a specified time interval.

public static System.Threading.Tasks.Task Delay (TimeSpan delay);

Parameters

delay
TimeSpan

The time span to wait before completing the returned task, or Timeout.InfiniteTimeSpan to wait indefinitely.

Returns

A task that represents the time delay.

Exceptions

delay represents a negative time interval other than Timeout.InfiniteTimeSpan.

-or-

The delay argument's TotalMilliseconds property is greater than 4294967294 on .NET 6 and later versions, or Int32.MaxValue on all previous versions.

Examples

The 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

Remarks

After the specified time delay, the task is completed in RanToCompletion state.

For usage scenarios and additional examples, see the documentation for the Delay(Int32) overload.

This method depends on the system clock. 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.

Бележка

The system clock that is used is the same clock used by GetTickCount, which is not affected by changes made with timeBeginPeriod and timeEndPeriod.

Applies to

.NET 9 и други версии
Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Delay(Int32, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

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

Parameters

millisecondsDelay
Int32

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.

Returns

A task that represents the time delay.

Exceptions

The millisecondsDelay argument is less than -1.

The task has been canceled. This exception is stored into the returned task.

The provided cancellationToken has already been disposed.

The task has been canceled.

Examples

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

Remarks

If the cancellation token is signaled before the specified time delay, a TaskCanceledException exception results, and the task is completed in the Canceled state. Otherwise, the task is completed in the RanToCompletion state once the specified time delay has elapsed.

For usage scenarios and additional examples, see the documentation for the Delay(Int32) overload.

This method depends on the system clock. 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.

Бележка

The system clock that is used is the same clock used by GetTickCount, which is not affected by changes made with timeBeginPeriod and timeEndPeriod.

Applies to

.NET 9 и други версии
Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Delay(TimeSpan, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a cancellable task that completes after a specified time interval.

public static System.Threading.Tasks.Task Delay (TimeSpan delay, System.Threading.CancellationToken cancellationToken);

Parameters

delay
TimeSpan

The time span to wait before completing the returned task, or Timeout.InfiniteTimeSpan to wait indefinitely.

cancellationToken
CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

A task that represents the time delay.

Exceptions

delay represents a negative time interval other than Timeout.InfiniteTimeSpan.

-or-

The delay argument's TotalMilliseconds property is greater than 4294967294 on .NET 6 and later versions, or Int32.MaxValue on all previous versions.

The task has been canceled. This exception is stored into the returned task.

The provided cancellationToken has already been disposed.

The task has been canceled.

Examples

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

Note that this example includes a potential race condition: it depends on the task asynchronously executing the delay when the token is cancelled. 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

Remarks

If the cancellation token is signaled before the specified time delay, a TaskCanceledException exception results, and the task is completed in the Canceled state. Otherwise, the task is completed in the RanToCompletion state once the specified time delay has elapsed.

For usage scenarios and additional examples, see the documentation for the Delay(Int32) overload.

This method depends on the system clock. 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.

Бележка

The system clock that is used is the same clock used by GetTickCount, which is not affected by changes made with timeBeginPeriod and timeEndPeriod.

Applies to

.NET 9 и други версии
Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Delay(TimeSpan, TimeProvider)

Source:
Task.cs
Source:
Task.cs

Creates a task that completes after a specified time interval.

public static System.Threading.Tasks.Task Delay (TimeSpan delay, TimeProvider timeProvider);

Parameters

delay
TimeSpan

The TimeSpan to wait before completing the returned task, or InfiniteTimeSpan to wait indefinitely.

timeProvider
TimeProvider

The TimeProvider with which to interpret delay.

Returns

A task that represents the time delay.

Exceptions

delay represents a negative time interval other than InfiniteTimeSpan.

-or-

delay's TotalMilliseconds property is greater than 4294967294.

The timeProvider argument is null.

Applies to

.NET 9 и .NET 8
Продукт Версии
.NET 8, 9

Delay(TimeSpan, TimeProvider, CancellationToken)

Source:
Task.cs
Source:
Task.cs

Creates a cancellable task that completes after a specified time interval.

public static System.Threading.Tasks.Task Delay (TimeSpan delay, TimeProvider timeProvider, System.Threading.CancellationToken cancellationToken);

Parameters

delay
TimeSpan

The TimeSpan to wait before completing the returned task, or InfiniteTimeSpan to wait indefinitely.

timeProvider
TimeProvider

The TimeProvider with which to interpret delay.

cancellationToken
CancellationToken

A cancellation token to observe while waiting for the task to complete.

Returns

A task that represents the time delay.

Exceptions

delay represents a negative time interval other than InfiniteTimeSpan.

-or-

delay's TotalMilliseconds property is greater than 4294967294.

The timeProvider argument is null.

The cancellation token was canceled. This exception is stored into the returned task.

Applies to

.NET 9 и .NET 8
Продукт Версии
.NET 8, 9