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
Assembly:  mscorlib (in mscorlib.dll)

[DebuggerDisplayAttribute("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public class Task : IAsyncResult, IDisposable

The Task type exposes the following members.

  NameDescription
Public methodSupported by Portable Class LibraryTask(Action)Initializes a new Task with the specified action.
Public methodSupported by Portable Class LibraryTask(Action, CancellationToken)Initializes a new Task with the specified action and CancellationToken.
Public methodSupported by Portable Class LibraryTask(Action, TaskCreationOptions)Initializes a new Task with the specified action and creation options.
Public methodSupported by Portable Class LibraryTask(Action<Object>, Object)Initializes a new Task with the specified action and state.
Public methodSupported by Portable Class LibraryTask(Action, CancellationToken, TaskCreationOptions)Initializes a new Task with the specified action and creation options.
Public methodSupported by Portable Class LibraryTask(Action<Object>, Object, CancellationToken)Initializes a new Task with the specified action, state, and options.
Public methodSupported by Portable Class LibraryTask(Action<Object>, Object, TaskCreationOptions)Initializes a new Task with the specified action, state, and options.
Public methodSupported by Portable Class LibraryTask(Action<Object>, Object, CancellationToken, TaskCreationOptions)Initializes a new Task with the specified action, state, and options.
Top

  NameDescription
Public propertySupported by Portable Class LibraryAsyncStateGets 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 LibraryCreationOptionsGets the TaskCreationOptions used to create this task.
Public propertyStatic memberSupported by Portable Class LibraryCurrentIdReturns the unique ID of the currently executing Task.
Public propertySupported by Portable Class LibraryExceptionGets 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 LibraryFactoryProvides access to factory methods for creating and configuring Task and Task<TResult> instances.
Public propertySupported by Portable Class LibraryIdGets a unique ID for this Task instance.
Public propertySupported by Portable Class LibraryIsCanceledGets whether this Task instance has completed execution due to being canceled.
Public propertySupported by Portable Class LibraryIsCompletedGets whether this Task has completed.
Public propertySupported by Portable Class LibraryIsFaultedGets whether the Task completed due to an unhandled exception.
Public propertySupported by Portable Class LibraryStatusGets the TaskStatus of this task.
Top

  NameDescription
Public methodConfigureAwaitConfigures an awaiter used to await this Task.
Public methodSupported by Portable Class LibraryContinueWith(Action<Task>)Creates a continuation that executes asynchronously when the target Task completes.
Public methodSupported by Portable Class LibraryContinueWith(Action<Task>, CancellationToken)Creates a continuation that executes asynchronously when the target Task completes.
Public methodSupported by Portable Class LibraryContinueWith(Action<Task>, TaskContinuationOptions)Creates a continuation that executes according to the specified TaskContinuationOptions.
Public methodSupported by Portable Class LibraryContinueWith(Action<Task>, TaskScheduler)Creates a continuation that executes asynchronously when the target Task completes.
Public methodContinueWith(Action<Task, Object>, Object)Creates a continuation that executes when the target Task completes.
Public methodContinueWith(Action<Task, Object>, Object, CancellationToken)Creates a continuation that executes when the target Task completes.
Public methodContinueWith(Action<Task, Object>, Object, TaskContinuationOptions)Creates a continuation that executes when the target Task completes.
Public methodContinueWith(Action<Task, Object>, Object, TaskScheduler)Creates a continuation that executes when the target Task completes.
Public methodSupported by Portable Class LibraryContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler)Creates a continuation that executes according to the specified TaskContinuationOptions.
Public methodContinueWith(Action<Task, Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)Creates a continuation that executes when the target Task completes.
Public methodSupported by Portable Class LibraryContinueWith<TResult>(Func<Task, TResult>)Creates a continuation that executes asynchronously when the target Task completes.
Public methodSupported by Portable Class LibraryContinueWith<TResult>(Func<Task, TResult>, CancellationToken)Creates a continuation that executes asynchronously when the target Task completes.
Public methodSupported by Portable Class LibraryContinueWith<TResult>(Func<Task, TResult>, TaskContinuationOptions)Creates a continuation that executes according to the condition specified in continuationOptions.
Public methodSupported by Portable Class LibraryContinueWith<TResult>(Func<Task, TResult>, TaskScheduler)Creates a continuation that executes asynchronously when the target Task completes.
Public methodContinueWith<TResult>(Func<Task, Object, TResult>, Object)Creates a continuation that executes when the target Task completes.
Public methodContinueWith<TResult>(Func<Task, Object, TResult>, Object, CancellationToken)Creates a continuation that executes when the target Task completes.
Public methodContinueWith<TResult>(Func<Task, Object, TResult>, Object, TaskContinuationOptions)Creates a continuation that executes when the target Task completes.
Public methodContinueWith<TResult>(Func<Task, Object, TResult>, Object, TaskScheduler)Creates a continuation that executes when the target Task completes.
Public methodSupported by Portable Class LibraryContinueWith<TResult>(Func<Task, TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)Creates a continuation that executes according to the condition specified in continuationOptions.
Public methodContinueWith<TResult>(Func<Task, Object, TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)Creates a continuation that executes when the target Task completes.
Public methodStatic memberDelay(Int32)Creates a task that completes after a time delay.
Public methodStatic memberDelay(TimeSpan)Creates a task that completes after a specified time interval.
Public methodStatic memberDelay(Int32, CancellationToken)Creates a cancellable task that completes after a time delay.
Public methodStatic memberDelay(TimeSpan, CancellationToken)Creates a cancellable task that completes after a specified time interval.
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 LibraryEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by Portable Class LibraryFinalizeAllows 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 memberFromResult<TResult>Creates a Task<TResult> that's completed successfully with the specified result.
Public methodGetAwaiterGets an awaiter used to await this Task.
Public methodSupported by Portable Class LibraryGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodSupported by Portable Class LibraryGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Portable Class LibraryMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodStatic memberRun(Action)Queues the specified work to run on the ThreadPool and returns a task handle for that work.
Public methodStatic memberRun(Func<Task>)Queues the specified work to run on the ThreadPool and returns a proxy for the task returned by function.
Public methodStatic memberRun(Action, CancellationToken)Queues the specified work to run on the ThreadPool and returns a task handle for that work.
Public methodStatic memberRun(Func<Task>, CancellationToken)Queues the specified work to run on the ThreadPool and returns a proxy for the task returned by function.
Public methodStatic memberRun<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 memberRun<TResult>(Func<TResult>)Queues the specified work to run on the thread pool and returns a Task<TResult> object that represents that work.
Public methodStatic memberRun<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 memberRun<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 LibraryRunSynchronously()Runs the Task synchronously on the current TaskScheduler.
Public methodSupported by Portable Class LibraryRunSynchronously(TaskScheduler)Runs the Task synchronously on the TaskScheduler provided.
Public methodSupported by Portable Class LibraryStart()Starts the Task, scheduling it for execution to the current TaskScheduler.
Public methodSupported by Portable Class LibraryStart(TaskScheduler)Starts the Task, scheduling it for execution to the specified TaskScheduler.
Public methodSupported by Portable Class LibraryToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodSupported by Portable Class LibraryWait()Waits for the Task to complete execution.
Public methodSupported by Portable Class LibraryWait(CancellationToken)Waits for the Task to complete execution. The wait terminates if a cancellation token is canceled before the task completes.
Public methodSupported by Portable Class LibraryWait(Int32)Waits for the Task to complete execution within a specified number of milliseconds.
Public methodSupported by Portable Class LibraryWait(TimeSpan)Waits for the Task to complete execution within a specified time interval.
Public methodSupported by Portable Class LibraryWait(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.
Public methodStatic memberSupported by Portable Class LibraryWaitAll(Task[])Waits for all of the provided Task objects to complete execution.
Public methodStatic memberSupported by Portable Class LibraryWaitAll(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 LibraryWaitAll(Task[], CancellationToken)Waits for all of the provided Task objects to complete execution unless the wait is cancelled.
Public methodStatic memberSupported by Portable Class LibraryWaitAll(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 LibraryWaitAll(Task[], Int32, CancellationToken)Waits for all of the provided Task objects to complete execution within a specified number of milliseconds or until the wait is cancelled.
Public methodStatic memberSupported by Portable Class LibraryWaitAny(Task[])Waits for any of the provided Task objects to complete execution.
Public methodStatic memberSupported by Portable Class LibraryWaitAny(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 LibraryWaitAny(Task[], CancellationToken)Waits for any of the provided Task objects to complete execution unless the wait is cancelled.
Public methodStatic memberSupported by Portable Class LibraryWaitAny(Task[], TimeSpan)Waits for any of the provided Task objects to complete execution within a specified time interval.
Public methodStatic memberSupported by Portable Class LibraryWaitAny(Task[], Int32, CancellationToken)Waits for any of the provided Task objects to complete execution within a specified number of milliseconds or until a cancellation token is cancelled.
Public methodStatic memberWhenAll(IEnumerable<Task>)Creates a task that will complete when all of the Task objects in an enumerable collection have completed.
Public methodStatic memberWhenAll(Task[])Creates a task that will complete when all of the Task objects in an array have completed.
Public methodStatic memberWhenAll<TResult>(IEnumerable<Task<TResult>>)Creates a task that will complete when all of the Task<TResult> objects in an enumerable collection have completed.
Public methodStatic memberWhenAll<TResult>(Task<TResult>[])Creates a task that will complete when all of the Task<TResult> objects in an array have completed.
Public methodStatic memberWhenAny(IEnumerable<Task>)Creates a task that will complete when any of the supplied tasks have completed.
Public methodStatic memberWhenAny(Task[])Creates a task that will complete when any of the supplied tasks have completed.
Public methodStatic memberWhenAny<TResult>(IEnumerable<Task<TResult>>)Creates a task that will complete when any of the supplied tasks have completed.
Public methodStatic memberWhenAny<TResult>(Task<TResult>[])Creates a task that will complete when any of the supplied tasks have completed.
Public methodStatic memberYieldCreates an awaitable task that asynchronously yields back to the current context when awaited.
Top

  NameDescription
Public Extension MethodAsAsyncActionReturns 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 LibraryIAsyncResult.AsyncWaitHandleGets a WaitHandle that can be used to wait for the task to complete.
Explicit interface implemetationPrivate propertySupported by Portable Class LibraryIAsyncResult.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.

The Task class represents a single operation that does not return a value and that usually executes asynchronously. Task objects are one of the central components of the task-based asynchronous programming pattern first introduced in the . Because the work performed by a Task object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the Status property, as well as the IsCanceled, IsCompleted, and IsFaulted properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform.

Task instances may be created in a variety of ways. The most common approach, which is available starting with the .NET Framework 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 parameters to pass to the 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 is the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, you can use the constructors and then call the Task.Start method to schedule the task for execution at a later time.

Starting with apps that target the .NET Framework 4.6 Preview, the culture of the thread that creates and invokes a task becomes part of the thread's context. That is, regardless of the current culture of the thread on which the task executes, the current culture of the task is the culture of the calling thread. For apps that target versions of the .NET Framework prior to the .NET Framework 4.6 Preview, the culture of the task is the culture of the thread on which the task executes. For more information, see the "Culture and task-based asynchronous operations" section in the CultureInfo topic.

For operations that return values, you use the Task<TResult> class.

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.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following example creates and executes four tasks. Three tasks execute an Action<T> delegate named action, which accepts an argument of type Object. A fourth task executes a lambda expression (an Action delegate) that is defined inline in the call to the task creation method. Each task is instantiated and run in a different way:

  • Task t1 is instantiated by calling a Task class constructor, but is started by calling its Start() method only after task t2 has started.

  • Task t2 is instantiated and started in a single method call by calling the TaskFactory.StartNew(Action<Object>, Object) method.

  • Task t3 is instantiated and started in a single method call by calling the Run(Action) method.

  • Task t4 is executed synchronously on the main thread by calling the RunSynchronously() method.

Because task t4 executes synchronously, it executes on the main application thread. The remaining tasks execute asynchronously typically on one or more thread pool threads.

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

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

        // Create a task but do not start it.
        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.
        t1.Wait();

        // Construct a started task using Task.Run.
        String taskData = "delta";
        Task t3 = Task.Run( () => {Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                                     Task.CurrentId, taskData,
                                                      Thread.CurrentThread.ManagedThreadId);
                                   });
        // Wait for the task to finish.
        t3.Wait();

        // Construct an unstarted task
        Task t4 = new Task(action, "gamma");
        // Run it synchronously
        t4.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.
        t4.Wait();
    }
}
// The example displays output like the following: 
//       Task=1, obj=beta, Thread=3 
//       t1 has been launched. (Main Thread=1) 
//       Task=2, obj=alpha, Thread=4 
//       Task=3, obj=delta, Thread=3 
//       Task=4, obj=gamma, Thread=1

.NET Framework

Supported in: 4.6, 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

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

Show:
© 2015 Microsoft