1 out of 1 rated this helpful - Rate this topic

Task Class

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

Represents an asynchronous operation.

System.Object
  System.Threading.Tasks.Task
    System.Threading.Tasks.Task<TResult>

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

[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public class Task : IAsyncResult, IDisposable

The Task type exposes the following members.

  Name Description
Public method Supported by Portable Class Library Task(Action) Initializes a new Task with the specified action.
Public method Supported by Portable Class Library Task(Action, CancellationToken) Initializes a new Task with the specified action and CancellationToken.
Public method Supported by Portable Class Library Task(Action, TaskCreationOptions) Initializes a new Task with the specified action and creation options.
Public method Supported by Portable Class Library Task(Action<Object>, Object) Initializes a new Task with the specified action and state.
Public method Supported by Portable Class Library Task(Action, CancellationToken, TaskCreationOptions) Initializes a new Task with the specified action and creation options.
Public method Supported by Portable Class Library Task(Action<Object>, Object, CancellationToken) Initializes a new Task with the specified action, state, and options.
Public method Supported by Portable Class Library Task(Action<Object>, Object, TaskCreationOptions) Initializes a new Task with the specified action, state, and options.
Public method Supported by Portable Class Library Task(Action<Object>, Object, CancellationToken, TaskCreationOptions) Initializes a new Task with the specified action, state, and options.
Top
  Name Description
Public property Supported by Portable Class Library AsyncState Gets the state object supplied when the Task was created, or null if none was supplied.
Public property Supported by Portable Class Library CreationOptions Gets the TaskCreationOptions used to create this task.
Public property Static member Supported by Portable Class Library CurrentId Returns the unique ID of the currently executing Task.
Public property Supported by Portable Class Library Exception Gets 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 property Static member Supported by Portable Class Library Factory Provides access to factory methods for creating Task and Task<TResult> instances.
Public property Supported by Portable Class Library Id Gets a unique ID for this Task instance.
Public property Supported by Portable Class Library IsCanceled Gets whether this Task instance has completed execution due to being canceled.
Public property Supported by Portable Class Library IsCompleted Gets whether this Task has completed.
Public property Supported by Portable Class Library IsFaulted Gets whether the Task completed due to an unhandled exception.
Public property Supported by Portable Class Library Status Gets the TaskStatus of this Task.
Top
  Name Description
Public method ConfigureAwait Configures an awaiter used to await this Task.
Public method Supported by Portable Class Library ContinueWith(Action<Task>) Creates a continuation that executes asynchronously when the target Task completes.
Public method Supported by Portable Class Library ContinueWith(Action<Task>, CancellationToken) Creates a continuation that executes asynchronously when the target Task completes.
Public method Supported by Portable Class Library ContinueWith(Action<Task>, TaskContinuationOptions) Creates a continuation that executes according to the specified TaskContinuationOptions.
Public method Supported by Portable Class Library ContinueWith(Action<Task>, TaskScheduler) Creates a continuation that executes asynchronously when the target Task completes.
Public method ContinueWith(Action<Task, Object>, Object) Creates a continuation that executes when the target Task completes.
Public method ContinueWith(Action<Task, Object>, Object, CancellationToken) Creates a continuation that executes when the target Task completes.
Public method ContinueWith(Action<Task, Object>, Object, TaskContinuationOptions) Creates a continuation that executes when the target Task completes.
Public method ContinueWith(Action<Task, Object>, Object, TaskScheduler) Creates a continuation that executes when the target Task completes.
Public method Supported by Portable Class Library ContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler) Creates a continuation that executes according to the specified TaskContinuationOptions.
Public method ContinueWith(Action<Task, Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) Creates a continuation that executes when the target Task completes.
Public method Supported by Portable Class Library ContinueWith<TResult>(Func<Task, TResult>) Creates a continuation that executes asynchronously when the target Task completes.
Public method Supported by Portable Class Library ContinueWith<TResult>(Func<Task, TResult>, CancellationToken) Creates a continuation that executes asynchronously when the target Task completes.
Public method Supported by Portable Class Library ContinueWith<TResult>(Func<Task, TResult>, TaskContinuationOptions) Creates a continuation that executes according to the condition specified in continuationOptions.
Public method Supported by Portable Class Library ContinueWith<TResult>(Func<Task, TResult>, TaskScheduler) Creates a continuation that executes asynchronously when the target Task completes.
Public method ContinueWith<TResult>(Func<Task, Object, TResult>, Object) Creates a continuation that executes when the target Task completes.
Public method ContinueWith<TResult>(Func<Task, Object, TResult>, Object, CancellationToken) Creates a continuation that executes when the target Task completes.
Public method ContinueWith<TResult>(Func<Task, Object, TResult>, Object, TaskContinuationOptions) Creates a continuation that executes when the target Task completes.
Public method ContinueWith<TResult>(Func<Task, Object, TResult>, Object, TaskScheduler) Creates a continuation that executes when the target Task completes.
Public method Supported by Portable Class Library ContinueWith<TResult>(Func<Task, TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler) Creates a continuation that executes according to the condition specified in continuationOptions.
Public method ContinueWith<TResult>(Func<Task, Object, TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) Creates a continuation that executes when the target Task completes.
Public method Static member Delay(Int32) Creates a Task that will complete after a time delay.
Public method Static member Delay(TimeSpan) Creates a Task that will complete after a time delay.
Public method Static member Delay(Int32, CancellationToken) Creates a Task that will complete after a time delay.
Public method Static member Delay(TimeSpan, CancellationToken) Creates a Task that will complete after a time delay.
Public method Dispose() Releases all resources used by the current instance of the Task class.
Protected method Dispose(Boolean) Disposes the Task, releasing all of its unmanaged resources.
Public method Supported by Portable Class Library Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by Portable Class Library Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Static member FromResult<TResult> Creates a Task<TResult> that's completed successfully with the specified result.
Public method GetAwaiter Gets an awaiter used to await this Task.
Public method Supported by Portable Class Library GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method Supported by Portable Class Library GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method Supported by Portable Class Library MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Static member Run(Action) Queues the specified work to run on the ThreadPool and returns a Task handle for that work.
Public method Static member Run(Func<Task>) Queues the specified work to run on the ThreadPool and returns a proxy for the Task returned by function.
Public method Static member Run(Action, CancellationToken) Queues the specified work to run on the ThreadPool and returns a Task handle for that work.
Public method Static member Run(Func<Task>, CancellationToken) Queues the specified work to run on the ThreadPool and returns a proxy for the Task returned by function.
Public method Static member Run<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 method Static member Run<TResult>(Func<TResult>) Queues the specified work to run on the ThreadPool and returns a Task(TResult) handle for that work.
Public method Static member Run<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 method Static member Run<TResult>(Func<TResult>, CancellationToken) Queues the specified work to run on the ThreadPool and returns a Task(TResult) handle for that work.
Public method Supported by Portable Class Library RunSynchronously() Runs the Task synchronously on the current TaskScheduler.
Public method Supported by Portable Class Library RunSynchronously(TaskScheduler) Runs the Task synchronously on the TaskScheduler provided.
Public method Supported by Portable Class Library Start() Starts the Task, scheduling it for execution to the current TaskScheduler.
Public method Supported by Portable Class Library Start(TaskScheduler) Starts the Task, scheduling it for execution to the specified TaskScheduler.
Public method Supported by Portable Class Library ToString Returns a string that represents the current object. (Inherited from Object.)
Public method Supported by Portable Class Library Wait() Waits for the Task to complete execution.
Public method Supported by Portable Class Library Wait(CancellationToken) Waits for the Task to complete execution.
Public method Supported by Portable Class Library Wait(Int32) Waits for the Task to complete execution.
Public method Supported by Portable Class Library Wait(TimeSpan) Waits for the Task to complete execution.
Public method Supported by Portable Class Library Wait(Int32, CancellationToken) Waits for the Task to complete execution.
Public method Static member Supported by Portable Class Library WaitAll(Task[]) Waits for all of the provided Task objects to complete execution.
Public method Static member Supported by Portable Class Library WaitAll(Task[], Int32) Waits for all of the provided Task objects to complete execution.
Public method Static member Supported by Portable Class Library WaitAll(Task[], CancellationToken) Waits for all of the provided Task objects to complete execution.
Public method Static member Supported by Portable Class Library WaitAll(Task[], TimeSpan) Waits for all of the provided Task objects to complete execution.
Public method Static member Supported by Portable Class Library WaitAll(Task[], Int32, CancellationToken) Waits for all of the provided Task objects to complete execution.
Public method Static member Supported by Portable Class Library WaitAny(Task[]) Waits for any of the provided Task objects to complete execution.
Public method Static member Supported by Portable Class Library WaitAny(Task[], Int32) Waits for any of the provided Task objects to complete execution.
Public method Static member Supported by Portable Class Library WaitAny(Task[], CancellationToken) Waits for any of the provided Task objects to complete execution.
Public method Static member Supported by Portable Class Library WaitAny(Task[], TimeSpan) Waits for any of the provided Task objects to complete execution.
Public method Static member Supported by Portable Class Library WaitAny(Task[], Int32, CancellationToken) Waits for any of the provided Task objects to complete execution.
Public method Static member WhenAll(IEnumerable<Task>) Creates a task that will complete when all of the supplied tasks have completed.
Public method Static member WhenAll(Task[]) Creates a task that will complete when all of the supplied tasks have completed.
Public method Static member WhenAll<TResult>(IEnumerable<Task<TResult>>) Creates a task that will complete when all of the supplied tasks have completed.
Public method Static member WhenAll<TResult>(Task<TResult>[]) Creates a task that will complete when all of the supplied tasks have completed.
Public method Static member WhenAny(IEnumerable<Task>) Creates a task that will complete when any of the supplied tasks have completed.
Public method Static member WhenAny(Task[]) Creates a task that will complete when any of the supplied tasks have completed.
Public method Static member WhenAny<TResult>(IEnumerable<Task<TResult>>) Creates a task that will complete when any of the supplied tasks have completed.
Public method Static member WhenAny<TResult>(Task<TResult>[]) Creates a task that will complete when any of the supplied tasks have completed.
Public method Static member Yield Creates an awaitable that asynchronously yields back to the current context when awaited.
Top
  Name Description
Public Extension Method AsAsyncAction Returns a Windows Runtime asynchronous action that represents a started task. (Defined by WindowsRuntimeSystemExtensions.)
Public Extension Method DispatcherOperationWait() Overloaded. Waits indefinitely for the underlying DispatcherOperation to complete. (Defined by TaskExtensions.)
Public Extension Method DispatcherOperationWait(TimeSpan) Overloaded. Waits for the specified amount of time for the underlying DispatcherOperation to complete. (Defined by TaskExtensions.)
Public Extension Method IsDispatcherOperationTask Returns a value that indicates whether this Task is associated with a DispatcherOperation. (Defined by TaskExtensions.)
Top
  Name Description
Explicit interface implemetation Private property Supported by Portable Class Library IAsyncResult.AsyncWaitHandle Gets a WaitHandle that can be used to wait for the task to complete.
Explicit interface implemetation Private property Supported by Portable Class Library IAsyncResult.CompletedSynchronously Gets an indication of whether the operation completed synchronously.
Top

Task instances may be created in a variety of ways. The most common approach is by using the Task type's Factory property to retrieve a TaskFactory instance that can be used to create tasks for several purposes. For example, to create a Task that runs an action, the factory's StartNew method may be used:

// C#
var t = Task.Factory.StartNew(() => DoAction());

' Visual Basic
 Dim t = Task.Factory.StartNew(Function() DoAction())

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, TaskFactory's 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's 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 Int32 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 Int32 counter is used to retrieve the next available ID for a Task). Similarly, the Int32 m_stateFlags field stores information about the current lifecycle stage of the Task, information also accessible through the Status property. The m_action System.Object field stores a reference to the Task's delegate, and the m_stateObject System.Object 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 shows how to start a task by using the System.Threading.Tasks.Task.Factory.StartNew method:


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

class StartNewDemo
{
    // 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.
    // Documentation:
    //		http://msdn.microsoft.com/en-us/library/system.threading.tasks.task_members(VS.100).aspx
    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");

        // Cosntruct 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 synchrounously, it is a good practice to wait for it which observes for 
        // exceptions potentially thrown by that task.
        t3.Wait();
    }


}


.NET Framework

Supported in: 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

Windows 8 Release Preview, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 SP2, 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.

Did you find this helpful?
(1500 characters remaining)