Export (0) Print
Expand All

Task Class

Represents an asynchronous operation.

To browse the .NET Framework source code for this type, see the Reference Source.

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

public class Task : IAsyncResult

The Task type exposes the following members.

  NameDescription
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTask(Action)Initializes a new Task with the specified action.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTask(Action, CancellationToken)Initializes a new Task with the specified action and CancellationToken.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTask(Action, TaskCreationOptions)Initializes a new Task with the specified action and creation options.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTask(Action<Object>, Object)Initializes a new Task with the specified action and state.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTask(Action, CancellationToken, TaskCreationOptions)Initializes a new Task with the specified action and creation options.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTask(Action<Object>, Object, CancellationToken)Initializes a new Task with the specified action, state, and options.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTask(Action<Object>, Object, TaskCreationOptions)Initializes a new Task with the specified action, state, and options.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTask(Action<Object>, Object, CancellationToken, TaskCreationOptions)Initializes a new Task with the specified action, state, and options.
Top

  NameDescription
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsAsyncStateGets the state object supplied when the Task was created, or null if none was supplied.
Public propertyStatic memberCompletedTaskGets a task that has already completed successfully.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsCreationOptionsGets the TaskCreationOptions used to create this task.
Public propertyStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsCurrentIdReturns the unique ID of the currently executing Task.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsExceptionGets the AggregateException that caused the Task to end prematurely. If the Task completed successfully or has not yet thrown any exceptions, this will return null.
Public propertyStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsFactoryProvides access to factory methods for creating Task and Task<TResult> instances.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsIdGets a unique ID for this Task instance.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsIsCanceledGets whether this Task instance has completed execution due to being canceled.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsIsCompletedGets whether this Task has completed.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsIsFaultedGets whether the Task completed due to an unhandled exception.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsStatusGets the TaskStatus of this task.
Top

  NameDescription
Public methodSupported in .NET for Windows Store appsConfigureAwaitConfigures an awaiter used to await this Task.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsContinueWith(Action<Task>)Creates a continuation that executes asynchronously when the target Task completes.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsContinueWith(Action<Task>, CancellationToken)Creates a continuation that executes asynchronously when the target Task completes.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsContinueWith(Action<Task>, TaskContinuationOptions)Creates a continuation that executes according to the specified TaskContinuationOptions.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsContinueWith(Action<Task>, TaskScheduler)Creates a continuation that executes asynchronously when the target Task completes.
Public methodSupported in .NET for Windows Store appsContinueWith(Action<Task, Object>, Object)Creates a continuation that executes when the target Task completes.
Public methodSupported in .NET for Windows Store appsContinueWith(Action<Task, Object>, Object, CancellationToken)Creates a continuation that executes when the target Task completes.
Public methodSupported in .NET for Windows Store appsContinueWith(Action<Task, Object>, Object, TaskContinuationOptions)Creates a continuation that executes when the target Task completes.
Public methodSupported in .NET for Windows Store appsContinueWith(Action<Task, Object>, Object, TaskScheduler)Creates a continuation that executes when the target Task completes.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler)Creates a continuation that executes according to the specified TaskContinuationOptions.
Public methodSupported in .NET for Windows Store appsContinueWith(Action<Task, Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)Creates a continuation that executes when the target Task completes.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsContinueWith<TResult>(Func<Task, TResult>)Creates a continuation that executes asynchronously when the target Task completes.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsContinueWith<TResult>(Func<Task, TResult>, CancellationToken)Creates a continuation that executes asynchronously when the target Task completes.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsContinueWith<TResult>(Func<Task, TResult>, TaskContinuationOptions)Creates a continuation that executes according to the condition specified in continuationOptions.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsContinueWith<TResult>(Func<Task, TResult>, TaskScheduler)Creates a continuation that executes asynchronously when the target Task completes.
Public methodSupported in .NET for Windows Store appsContinueWith<TResult>(Func<Task, Object, TResult>, Object)Creates a continuation that executes when the target Task completes.
Public methodSupported in .NET for Windows Store appsContinueWith<TResult>(Func<Task, Object, TResult>, Object, CancellationToken)Creates a continuation that executes when the target Task completes.
Public methodSupported in .NET for Windows Store appsContinueWith<TResult>(Func<Task, Object, TResult>, Object, TaskContinuationOptions)Creates a continuation that executes when the target Task completes.
Public methodSupported in .NET for Windows Store appsContinueWith<TResult>(Func<Task, Object, TResult>, Object, TaskScheduler)Creates a continuation that executes when the target Task completes.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsContinueWith<TResult>(Func<Task, TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)Creates a continuation that executes according to the condition specified in continuationOptions.
Public methodSupported in .NET for Windows Store appsContinueWith<TResult>(Func<Task, Object, TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)Creates a continuation that executes when the target Task completes.
Public methodStatic memberSupported in .NET for Windows Store appsDelay(Int32)Creates a task that will complete after a time delay.
Public methodStatic memberSupported in .NET for Windows Store appsDelay(TimeSpan)Creates a task that will complete after a time delay.
Public methodStatic memberSupported in .NET for Windows Store appsDelay(Int32, CancellationToken)Creates a task that will complete after a time delay.
Public methodStatic memberSupported in .NET for Windows Store appsDelay(TimeSpan, CancellationToken)Creates a task that will complete after a time delay.
Public methodDispose()Releases all resources used by the current instance of the Task class.
Protected methodDispose(Boolean)Disposes the Task, releasing all of its unmanaged resources.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodStatic memberFromCanceled(CancellationToken)Creates a Task that's completed due to cancellation with a specified cancellation token.
Public methodStatic memberFromCanceled<TResult>(CancellationToken)Creates a Task<TResult> that's completed due to cancellation with a specified cancellation token.
Public methodStatic memberFromException(Exception)Creates a Task that has completed with a specified exception.
Public methodStatic memberFromException<TResult>(Exception)Creates a Task<TResult> that's completed with a specified exception.
Public methodStatic memberSupported in .NET for Windows Store appsFromResult<TResult>Creates a Task<TResult> that's completed successfully with the specified result.
Public methodSupported in .NET for Windows Store appsGetAwaiterGets an awaiter used to await this Task.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodStatic memberSupported in .NET for Windows Store appsRun(Action)Queues the specified work to run on the ThreadPool and returns a task handle for that work.
Public methodStatic memberSupported in .NET for Windows Store appsRun(Func<Task>)Queues the specified work to run on the ThreadPool and returns a proxy for the task returned by function.
Public methodStatic memberSupported in .NET for Windows Store appsRun(Action, CancellationToken)Queues the specified work to run on the ThreadPool and returns a task handle for that work.
Public methodStatic memberSupported in .NET for Windows Store appsRun(Func<Task>, CancellationToken)Queues the specified work to run on the ThreadPool and returns a proxy for the task returned by function.
Public methodStatic memberSupported in .NET for Windows Store appsRun<TResult>(Func<Task<TResult>>)Queues the specified work to run on the ThreadPool and returns a proxy for the Task(TResult) returned by function.
Public methodStatic memberSupported in .NET for Windows Store appsRun<TResult>(Func<TResult>)Queues the specified work to run on the ThreadPool and returns a Task(TResult) handle for that work.
Public methodStatic memberSupported in .NET for Windows Store appsRun<TResult>(Func<Task<TResult>>, CancellationToken)Queues the specified work to run on the ThreadPool and returns a proxy for the Task(TResult) returned by function.
Public methodStatic memberSupported in .NET for Windows Store appsRun<TResult>(Func<TResult>, CancellationToken)Queues the specified work to run on the thread pool and returns a Task(TResult) handle for that work.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsRunSynchronously()Runs the Task synchronously on the current TaskScheduler.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsRunSynchronously(TaskScheduler)Runs the Task synchronously on the TaskScheduler provided.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsStart()Starts the Task, scheduling it for execution to the current TaskScheduler.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsStart(TaskScheduler)Starts the Task, scheduling it for execution to the specified TaskScheduler.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsWait()Waits for the Task to complete execution.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsWait(CancellationToken)Waits for the cancellable Task to complete execution.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsWait(Int32)Waits for the Task to complete execution within a specified number of milliseconds.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsWait(TimeSpan)Waits for the Task to complete execution within a specified time interval.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsWait(Int32, CancellationToken)Waits for the cancellable Task to complete execution.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitAll(Task[])Waits for all of the provided Task objects to complete execution.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitAll(Task[], Int32)Waits for all of the provided Task objects to complete execution within a specified number of milliseconds.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitAll(Task[], CancellationToken)Waits for all of the provided cancellable Task objects to complete execution.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitAll(Task[], TimeSpan)Waits for all of the provided cancellable Task objects to complete execution within a specified time interval.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitAll(Task[], Int32, CancellationToken)Waits for all of the provided cancellable Task objects to complete execution within a specified number of milliseconds.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitAny(Task[])Waits for any of the provided Task objects to complete execution.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitAny(Task[], Int32)Waits for any of the provided Task objects to complete execution within a specified number of milliseconds.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitAny(Task[], CancellationToken)Waits for any of the provided cancellable Task objects to complete execution.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitAny(Task[], TimeSpan)Waits for any of the provided Task objects to complete execution within a specified time interval.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitAny(Task[], Int32, CancellationToken)Waits for any of the provided cancellable Task objects to complete execution within a specified number of milliseconds.
Public methodStatic memberSupported in .NET for Windows Store appsWhenAll(IEnumerable<Task>)Creates a task that will complete when all of the supplied tasks have completed.
Public methodStatic memberSupported in .NET for Windows Store appsWhenAll(Task[])Creates a task that will complete when all of the supplied tasks have completed.
Public methodStatic memberSupported in .NET for Windows Store appsWhenAll<TResult>(IEnumerable<Task<TResult>>)Creates a task that will complete when all of the supplied tasks have completed.
Public methodStatic memberSupported in .NET for Windows Store appsWhenAll<TResult>(Task<TResult>[])Creates a task that will complete when all of the supplied tasks have completed.
Public methodStatic memberSupported in .NET for Windows Store appsWhenAny(IEnumerable<Task>)Creates a task that will complete when any of the supplied tasks have completed.
Public methodStatic memberSupported in .NET for Windows Store appsWhenAny(Task[])Creates a task that will complete when any of the supplied tasks have completed.
Public methodStatic memberSupported in .NET for Windows Store appsWhenAny<TResult>(IEnumerable<Task<TResult>>)Creates a task that will complete when any of the supplied tasks have completed.
Public methodStatic memberSupported in .NET for Windows Store appsWhenAny<TResult>(Task<TResult>[])Creates a task that will complete when any of the supplied tasks have completed.
Public methodStatic memberSupported in .NET for Windows Store appsYieldCreates an awaitable task that asynchronously yields back to the current context when awaited.
Top

  NameDescription
Public Extension MethodSupported in .NET for Windows Store appsAsAsyncActionReturns a Windows Runtime asynchronous action that represents a started task. (Defined by WindowsRuntimeSystemExtensions.)
Public Extension MethodDispatcherOperationWait()Overloaded. Waits indefinitely for the underlying DispatcherOperation to complete. (Defined by TaskExtensions.)
Public Extension MethodDispatcherOperationWait(TimeSpan)Overloaded. Waits for the specified amount of time for the underlying DispatcherOperation to complete. (Defined by TaskExtensions.)
Public Extension MethodIsDispatcherOperationTaskReturns a value that indicates whether this Task is associated with a DispatcherOperation. (Defined by TaskExtensions.)
Top

  NameDescription
Explicit interface implemetationPrivate propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsIAsyncResult.AsyncWaitHandleGets a WaitHandle that can be used to wait for the task to complete.
Explicit interface implemetationPrivate propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsIAsyncResult.CompletedSynchronouslyGets an indication of whether the operation completed synchronously.
Top

NoteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

Task instances may be created in a variety of ways. The most common approach, which is available starting with 4.6 Preview, 4.5.2, 4.5.1, 4.5, is to call the static Run method. The Run method provides a simple way to start a task using default values and without requiring additional parameters. The following example uses the Run(Action) method to start a task that loops and then displays the number of loop iterations:

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Run( () => {
                                  // Just loop. 
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
      t.Wait();
   }
}
// The example displays the following output: 
//        Finished 1000001 loop iterations

An alternative, and the most common method to start a task in .NET Framework 4, is the static TaskFactory.StartNew method. The Task.Factory property returns a TaskFactory object. Overloads of the TaskFactory.StartNew method let you specify task creation options and a task scheduler. The following example uses the TaskFactory.StartNew method to start a task. It is functionally equivalent to the code in the previous example.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Factory.StartNew( () => {
                                  // Just loop. 
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
      t.Wait();
   }
}
// The example displays the following output: 
//        Finished 1000001 loop iterations

For more complete examples, see Task Parallelism (Task Parallel Library).

The Task class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the Task.Run or TaskFactory.StartNew method should be the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, the constructors may be used, and the Task.Start method may then be used to schedule the task for execution at a later time.

For operations that return values, the Task<TResult> class should be used.

For Debugger Developers

For developers implementing custom debuggers, several internal and private members of task may be useful (these may change from release to release). The m_taskId field serves as the backing store for the Id property, however accessing this field directly from a debugger may be more efficient than accessing the same value through the property's getter method (the s_taskIdCounter counter is used to retrieve the next available ID for a task). Similarly, the m_stateFlags field stores information about the current lifecycle stage of the task, information also accessible through the Status property. The m_action field stores a reference to the task's delegate, and the m_stateObject field stores the async state passed to the task by the developer. Finally, for debuggers that parse stack frames, the InternalWait method serves a potential marker for when a task is entering a wait operation.

The following example shows how to start a task by using the TaskFactory.StartNew method:

// Demonstrated features: 
//		Task ctor() 
// 		Task.Factory 
//		Task.Wait() 
//		Task.RunSynchronously() 
// Expected results: 
// 		Task t1 (alpha) is created unstarted. 
//		Task t2 (beta) is created started. 
//		Task t1's (alpha) start is held until after t2 (beta) is started. 
//		Both tasks t1 (alpha) and t2 (beta) are potentially executed on  
//           threads other than the main thread on multi-core machines. 
//		Task t3 (gamma) is executed synchronously on the main thread. 
using System;
using System.Threading;
using System.Threading.Tasks;

class StartNewDemo
{
    static void Main()
    {
        Action<object> action = (object obj) =>
        {
            Console.WriteLine("Task={0}, obj={1}, Thread={2}", 
                              Task.CurrentId, obj.ToString(), 
                              Thread.CurrentThread.ManagedThreadId);
        };

        // Construct an unstarted task
        Task t1 = new Task(action, "alpha");

        // Construct a started task
        Task t2 = Task.Factory.StartNew(action, "beta");

        // Block the main thread to demonstate that t2 is executing
        t2.Wait();

        // Launch t1 
        t1.Start();

        Console.WriteLine("t1 has been launched. (Main Thread={0})", 
                          Thread.CurrentThread.ManagedThreadId);

        // Wait for the task to finish. 
        // You may optionally provide a timeout interval or a cancellation token 
        // to mitigate situations when the task takes too long to finish.
        t1.Wait();

        // Construct an unstarted task
        Task t3 = new Task(action, "gamma");

        // Run it synchronously
        t3.RunSynchronously();

        // Although the task was run synchronously, it is a good practice 
        // to wait for it in the event exceptions were thrown by the task.
        t3.Wait();
    }
}

.NET Framework

Supported in: 4.6, 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

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

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.

All members of Task, except for Dispose, are thread-safe and may be used from multiple threads concurrently.

Show:
© 2014 Microsoft