Task::Run Method (Action^, CancellationToken)

.NET Framework (current version)

Queues the specified work to run on the thread pool and returns a Task object that represents that work. A cancellation token allows the work to be cancelled.

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

static Task^ Run(
	Action^ action,
	CancellationToken cancellationToken


Type: System::Action^

The work to execute asynchronously

Type: System.Threading::CancellationToken

A cancellation token that can be used to cancel the work

Return Value

Type: System.Threading.Tasks::Task^

A task that represents the work queued to execute in the thread pool.

Exception Condition

The action parameter was null.


The task has been canceled.


The CancellationTokenSource associated with cancellationToken was disposed.

If cancellation is requested before the task begins execution, the task does not execute. Instead it is set to the Canceled state and throws a TaskCanceledException exception.

The Run(Action^, CancellationToken) method is a simpler alternative to the TaskFactory::StartNew(Action^, CancellationToken) method. It creates a task with the following default values:

For information on handling exceptions thrown by task operations, see Exception Handling (Task Parallel Library).

The following example calls the Run(Action^, CancellationToken) method 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.

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

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