Task.Run Method (Action, CancellationToken)

.NET Framework (current version)

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

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)

public 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.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class Example
   public static void Main()
      var tokenSource = new CancellationTokenSource();
      var token = tokenSource.Token;
      var files = new List<Tuple<string, string, long, DateTime>>();

      var t = Task.Run( () => { string dir = "C:\\Windows\\System32\\";
                                object obj = new Object();
                                if (Directory.Exists(dir)) {
                                   f => {
                                           if (token.IsCancellationRequested)
                                           var fi = new FileInfo(f);
                                           lock(obj) {
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc));          
                        , token);
      try {
         Console.WriteLine("Retrieved information for {0} files.", files.Count);
      catch (AggregateException e) {
         Console.WriteLine("Exception messages:");
         foreach (var ie in e.InnerExceptions)
            Console.WriteLine("   {0}: {1}", ie.GetType().Name, ie.Message);

         Console.WriteLine("\nTask status: {0}", t.Status);       
      finally {
// The example displays the following output:
//       Exception messages:
//          TaskCanceledException: A task was canceled.
//       Task status: Canceled

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