Task.Run Method (Action, CancellationToken)

.NET Framework 4.5

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

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

public static Task Run(
	Action action,
	CancellationToken cancellationToken
)

Parameters

action
Type: System.Action

The work to execute asynchronously

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

ExceptionCondition
ArgumentNullException

The action parameter was null.

TaskCanceledException

The task has been canceled.

ObjectDisposedException

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)) {
                                   Parallel.ForEach(Directory.GetFiles(dir),
                                   f => {
                                           if (token.IsCancellationRequested)
                                              token.ThrowIfCancellationRequested();
                                           var fi = new FileInfo(f);
                                           lock(obj) {
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc));          
                                           }
                                      });
                                 }
                              }
                        , token);
      tokenSource.Cancel();
      try {
         t.Wait(); 
         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);       
      }
   }
}
// The example displays the following output: 
//       Exception messages: 
//          TaskCanceledException: A task was canceled. 
//        
//       Task status: Canceled

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft