Task Constructor (Action^, CancellationToken)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Initializes a new Task with the specified action and CancellationToken.

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

	Action^ action,
	CancellationToken cancellationToken


Type: System::Action^

The delegate that represents the code to execute in the task.

Type: System.Threading::CancellationToken

The CancellationToken that the new task will observe.

Exception Condition

The provided CancellationToken has already been disposed.


The action argument is null.

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static Task::Run(Action^, CancellationToken) and TaskFactory::StartNew(Action^, CancellationToken) methods. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

For more information, see Task Parallelism (Task Parallel Library) and Cancellation in Managed Threads.

The following example calls the Task(Action^, CancellationToken) constructor to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the Parallel::ForEach<TSource> method to add information about each file to a List<T> object. Each detached nested task invoked by the Parallel::ForEach<TSource> loop checks the state of the cancellation token and, if cancellation is requested, calls the CancellationToken::ThrowIfCancellationRequested method. The CancellationToken::ThrowIfCancellationRequested method throws an OperationCanceledException exception that is handled in a catch block when the calling thread calls the Task::Wait method. The Start method is then called to start the task.

No code example is currently available or this language may not be supported.

Universal Windows Platform
Available since 8
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Available since 5.0
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top