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)

public static Task Run(
	Action action,
	CancellationToken cancellationToken


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


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.

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

.NET Framework

Supported in: 4.6, 4.5

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2015 Microsoft