Export (0) Print
Expand All
0 out of 4 rated this helpful - Rate this topic

Task.Wait Method

Waits for the Task to complete execution.

Namespace:  System.Threading.Tasks
Assembly:  mscorlib (in mscorlib.dll)
public void Wait()
ExceptionCondition
ObjectDisposedException

The Task has been disposed.

AggregateException

The Task was canceled -or- an exception was thrown during the execution of the Task. If the task was canceled, the AggregateException contains an OperationCanceledException in its InnerExceptions collection.

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

.NET Framework

Supported in: 4.5.1, 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

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

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.