Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

Task.Run Method (Action, CancellationToken)

.NET Framework 4.6 and 4.5

Queues the specified work to run on the ThreadPool and returns a task handle for that work.

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

static member Run : 
        action:Action * 
        cancellationToken:CancellationToken -> Task


Type: System.Action

The work to execute asynchronously

Type: System.Threading.CancellationToken

A cancellation token that should be used to cancel the work

Return Value

Type: System.Threading.Tasks.Task
A task that represents the work queued to execute in the ThreadPool.


The action parameter was a null reference (Nothing in Visual Basic).


The task has been canceled.


The CancellationTokenSource associated with cancellationToken was disposed.

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:

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 method to add information about each file to a List(T) object. Each detached nested task invoked by the Parallel.ForEach 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.

.NET Framework

Supported in: 4.6, 4.5

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
© 2015 Microsoft