Task.Wait Method

Waits for the Task to complete execution.

Namespace:  System.Threading.Tasks
Assemblies:   System.Threading.Tasks (in System.Threading.Tasks.dll)
  mscorlib (in mscorlib.dll)

public void Wait()


The Task has been disposed.


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


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

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.

For more information and an example, see How to: Wait on One or More Tasks to Complete.

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);   
                         } );
// The example displays output similar to the following: 
//       Total:   50,015,714 
//       Mean:    50.02 
//       N:       1,000,000

.NET Framework

Supported in: 4.6, 4.5, 4

.NET Framework Client Profile

Supported in: 4

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Portable Class Library

Supported in: Portable Class Library
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2015 Microsoft