Task.Wait Method

Definition

Waits for the Task to complete execution.

Overloads

Wait(TimeSpan, CancellationToken)

Waits for the Task to complete execution.

Wait(Int32, CancellationToken)

Waits for the Task to complete execution. The wait terminates if a timeout interval elapses or a cancellation token is canceled before the task completes.

Wait(TimeSpan)

Waits for the Task to complete execution within a specified time interval.

Wait(CancellationToken)

Waits for the Task to complete execution. The wait terminates if a cancellation token is canceled before the task completes.

Wait()

Waits for the Task to complete execution.

Wait(Int32)

Waits for the Task to complete execution within a specified number of milliseconds.

Wait(TimeSpan, CancellationToken)

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

Waits for the Task to complete execution.

public bool Wait (TimeSpan timeout, System.Threading.CancellationToken cancellationToken);

Parameters

timeout
TimeSpan

The time to wait, or InfiniteTimeSpan to wait indefinitely

cancellationToken
CancellationToken

A CancellationToken to observe while waiting for the task to complete.

Returns

true if the Task completed execution within the allotted time; otherwise, false.

Exceptions

The Task was canceled

-or-

an exception was thrown during the execution of the Task.

timeout is a negative number other than -1 milliseconds, which represents an infinite time-out

-or-

timeout is greater than MaxValue.

The cancellationToken was canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET 7, 8, 9

Wait(Int32, CancellationToken)

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

Waits for the Task to complete execution. The wait terminates if a timeout interval elapses or a cancellation token is canceled before the task completes.

public bool Wait (int millisecondsTimeout, System.Threading.CancellationToken cancellationToken);

Parameters

millisecondsTimeout
Int32

The number of milliseconds to wait, or Infinite (-1) to wait indefinitely.

cancellationToken
CancellationToken

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

Returns

true if the Task completed execution within the allotted time; otherwise, false.

Exceptions

The cancellationToken was canceled.

The Task has been disposed.

millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.

The task was canceled. The InnerExceptions collection contains a TaskCanceledException object.

-or-

An exception was thrown during the execution of the task. The InnerExceptions collection contains information about the exception or exceptions.

Examples

The following example calls the Wait(Int32, CancellationToken) method to provide both a timeout value and a cancellation token that can end the wait for a task's completion. A new thread is started and executes the CancelToken method, which pauses and then calls the CancellationTokenSource.Cancel method to cancel the cancellation tokens. A task is then launched and delays for 5 seconds. The Wait method is then called to wait for the task's completion and is provided both a brief timeout value and a cancellation token.

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      CancellationTokenSource ts = new CancellationTokenSource();
      Thread thread = new Thread(CancelToken);
      thread.Start(ts);

      Task t = Task.Run( () => { Task.Delay(5000).Wait();
                                 Console.WriteLine("Task ended delay...");
                               });
      try {
         Console.WriteLine("About to wait completion of task {0}", t.Id);
         bool result = t.Wait(1510, ts.Token);
         Console.WriteLine("Wait completed normally: {0}", result);
         Console.WriteLine("The task status:  {0:G}", t.Status);
      }
      catch (OperationCanceledException e) {
         Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
                           e.GetType().Name, t.Status);
         Thread.Sleep(4000);
         Console.WriteLine("After sleeping, the task status:  {0:G}", t.Status);
         ts.Dispose();
      }
   }

   private static void CancelToken(Object obj)
   {
      Thread.Sleep(1500);
      Console.WriteLine("Canceling the cancellation token from thread {0}...",
                        Thread.CurrentThread.ManagedThreadId);
      CancellationTokenSource source = obj as CancellationTokenSource;
      if (source != null) source.Cancel();
   }
}
// The example displays output like the following if the wait is canceled by
// the cancellation token:
//    About to wait completion of task 1
//    Canceling the cancellation token from thread 3...
//    OperationCanceledException: The wait has been canceled. Task status: Running
//    Task ended delay...
//    After sleeping, the task status:  RanToCompletion
// The example displays output like the following if the wait is canceled by
// the timeout interval expiring:
//    About to wait completion of task 1
//    Wait completed normally: False
//    The task status:  Running
//    Canceling the cancellation token from thread 3...

Note that the precise output from the example depends on whether the wait was canceled because of the cancellation token or because the timeout interval elapsed.

Remarks

Wait(Int32, CancellationToken) is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs:

Note

Canceling the cancellationToken cancellation token has no effect on the running task unless it has also been passed the cancellation token and is prepared to handle cancellation. Passing the cancellationToken object to this method simply allows the wait to be canceled based on some condition.

Applies to

.NET 9 and other versions
Product Versions
.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.0, 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

Wait(TimeSpan)

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

Waits for the Task to complete execution within a specified time interval.

public bool Wait (TimeSpan timeout);

Parameters

timeout
TimeSpan

A TimeSpan that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.

Returns

true if the Task completed execution within the allotted time; otherwise, false.

Exceptions

The Task has been disposed.

timeout is a negative number other than -1 milliseconds, which represents an infinite time-out.

-or-

timeout is greater than Int32.MaxValue.

The task was canceled. The InnerExceptions collection contains a TaskCanceledException object.

-or-

An exception was thrown during the execution of the task. The InnerExceptions collection contains information about the exception or exceptions.

Examples

The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. The example uses the Wait(TimeSpan) method to wait for the application to complete within 150 milliseconds. If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. If the timeout interval has elapsed, the example displays a message before it terminates.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Run( () => {
                            Random rnd = new Random();
                            long sum = 0;
                            int n = 5000000;
                            for (int ctr = 1; ctr <= n; ctr++) {
                               int number = rnd.Next(0, 101);
                               sum += number;
                            }
                            Console.WriteLine("Total:   {0:N0}", sum);
                            Console.WriteLine("Mean:    {0:N2}", sum/n);
                            Console.WriteLine("N:       {0:N0}", n);   
                         } );
     TimeSpan ts = TimeSpan.FromMilliseconds(150);
     if (!t.Wait(ts))
        Console.WriteLine("The timeout interval elapsed.");
   }
}
// The example displays output similar to the following:
//       Total:   50,015,714
//       Mean:    50.02
//       N:       1,000,000
// Or it displays the following output:
//      The timeout interval elapsed.

Remarks

Wait(TimeSpan) is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs:

  • The task completes successfully.

  • The task itself is canceled or throws an exception. In this case, you handle an AggregateException exception. The AggregateException.InnerExceptions property contains details about the exception or exceptions.

  • The interval defined by timeout elapses. In this case, the current thread resumes execution and the method returns false.

Applies to

.NET 9 and other versions
Product Versions
.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.0, 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

Wait(CancellationToken)

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

Waits for the Task to complete execution. The wait terminates if a cancellation token is canceled before the task completes.

public void Wait (System.Threading.CancellationToken cancellationToken);

Parameters

cancellationToken
CancellationToken

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

Exceptions

The cancellationToken was canceled.

The task has been disposed.

The task was canceled. The InnerExceptions collection contains a TaskCanceledException object.

-or-

An exception was thrown during the execution of the task. The InnerExceptions collection contains information about the exception or exceptions.

Examples

The following example illustrates the simple use of a cancellation token to cancel waiting for a task's completion. A task is launched, calls the CancellationTokenSource.Cancel method to cancel any of the token source's cancellation tokens, and then delays for five seconds. Note that the task itself has not been passed the cancellation token and is not cancelable. The application thread calls the task's Task.Wait method to wait for the task to complete, but the wait is canceled once the cancellation token is cancelled and an OperationCanceledException is thrown. The exception handler reports the exception and then sleeps for six seconds. As the output from the example shows, that delay allows the task to complete in the RanToCompletion state.

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      CancellationTokenSource ts = new CancellationTokenSource();

      Task t = Task.Run( () => { Console.WriteLine("Calling Cancel...");
                                 ts.Cancel();
                                 Task.Delay(5000).Wait();
                                 Console.WriteLine("Task ended delay...");
                               });
      try {
         Console.WriteLine("About to wait for the task to complete...");
         t.Wait(ts.Token);
      }
      catch (OperationCanceledException e) {
         Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
                           e.GetType().Name, t.Status);
         Thread.Sleep(6000);
         Console.WriteLine("After sleeping, the task status:  {0:G}", t.Status);
      }
      ts.Dispose();
   }
}
// The example displays output like the following:
//    About to wait for the task to complete...
//    Calling Cancel...
//    OperationCanceledException: The wait has been canceled. Task status: Running
//    Task ended delay...
//    After sleeping, the task status:  RanToCompletion

Remarks

The Wait(CancellationToken) method creates a cancelable wait; that is, it causes the current thread to wait until one of the following occurs:

Note

Canceling the cancellationToken cancellation token has no effect on the running task unless it has also been passed the cancellation token and is prepared to handle cancellation. Passing the cancellationToken object to this method simply allows the wait to be canceled.

Applies to

.NET 9 and other versions
Product Versions
.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.0, 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

Wait()

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

Waits for the Task to complete execution.

public void Wait ();

Exceptions

The Task has been disposed.

The task was canceled. The InnerExceptions collection contains a TaskCanceledException object.

-or-

An exception was thrown during the execution of the task. The InnerExceptions collection contains information about the exception or exceptions.

Examples

The following example starts a task that generates one million random integers between 0 and 100 and computes their mean. The example uses the Wait method to ensure that the task completes before the application terminates. Otherwise, because this is a console application, the example would terminate before the task can compute and display the mean.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Run( () => {
                            Random rnd = new Random();
                            long sum = 0;
                            int n = 1000000;
                            for (int ctr = 1; ctr <= n; ctr++) {
                               int number = rnd.Next(0, 101);
                               sum += number;
                            }
                            Console.WriteLine("Total:   {0:N0}", sum);
                            Console.WriteLine("Mean:    {0:N2}", sum/n);
                            Console.WriteLine("N:       {0:N0}", n);   
                         } );
     t.Wait();
   }
}
// The example displays output similar to the following:
//       Total:   50,015,714
//       Mean:    50.02
//       N:       1,000,000

Remarks

Wait is a synchronization method that causes the calling thread to wait until the current task has completed. If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread. If it is unable to do that, or if the current task has already started execution, it blocks the calling thread until the task completes. For more information, see Task.Wait and "Inlining" in the Parallel Programming with .NET blog.

See also

Applies to

.NET 9 and other versions
Product Versions
.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.0, 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

Wait(Int32)

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

Waits for the Task to complete execution within a specified number of milliseconds.

public bool Wait (int millisecondsTimeout);

Parameters

millisecondsTimeout
Int32

The number of milliseconds to wait, or Infinite (-1) to wait indefinitely.

Returns

true if the Task completed execution within the allotted time; otherwise, false.

Exceptions

The Task has been disposed.

millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.

The task was canceled. The InnerExceptions collection contains a TaskCanceledException object.

-or-

An exception was thrown during the execution of the task. The InnerExceptions collection contains information about the exception or exceptions.

Examples

The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. The example uses the Wait(Int32) method to wait for the application to complete within 150 milliseconds. If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. If the timeout interval has elapsed, the example displays a message before it terminates.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Run( () => {
                            Random rnd = new Random();
                            long sum = 0;
                            int n = 5000000;
                            for (int ctr = 1; ctr <= n; ctr++) {
                               int number = rnd.Next(0, 101);
                               sum += number;
                            }
                            Console.WriteLine("Total:   {0:N0}", sum);
                            Console.WriteLine("Mean:    {0:N2}", sum/n);
                            Console.WriteLine("N:       {0:N0}", n);   
                         } );
     if (!t.Wait(150))
        Console.WriteLine("The timeout interval elapsed.");
   }
}
// The example displays output similar to the following:
//       Total:   50,015,714
//       Mean:    50.02
//       N:       1,000,000
// Or it displays the following output:
//      The timeout interval elapsed.

Remarks

Wait(Int32) is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs:

  • The task completes successfully.

  • The task itself is canceled or throws an exception. In this case, you handle an AggregateException exception. The AggregateException.InnerExceptions property contains details about the exception or exceptions.

  • The interval defined by millisecondsTimeout elapses. In this case, the current thread resumes execution and the method returns false.

Applies to

.NET 9 and other versions
Product Versions
.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.0, 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