The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Task.Run<TResult> Method (Func<TResult>, CancellationToken)

.NET Framework 4.6 and 4.5

Queues the specified work to run on the thread pool and returns a Task(TResult) 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<TResult> Run<TResult>(
	Func<TResult> function,
	CancellationToken cancellationToken


Type: System.Func<TResult>

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<TResult>

A Task(TResult) that represents the work queued to execute in the thread pool.

Type Parameters


The result type of the task.

Exception Condition

The function parameter is 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<TResult> method is a simpler alternative to the StartNew 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 creates 20 tasks that will loop until a counter is incremented to a value of 2 million. When the first 10 tasks reach 2 million, the cancellation token is cancelled, and any tasks whose counters have not reached 2 million are cancelled. The example shows possible output.

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

public class Example
   public static void Main()
      var tasks = new List<Task<int>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      int completedIterations = 0;

      for (int n = 0; n <= 19; n++)
         tasks.Add(Task.Run( () => { int iterations = 0;
                                     for (int ctr = 1; ctr <= 2000000; ctr++) {
                                     Interlocked.Increment(ref completedIterations);
                                     if (completedIterations >= 10)
                                     return iterations; }, token));

      Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
      try  {
      catch (AggregateException) {
         Console.WriteLine("Status of tasks:\n");
         Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
                           "Status", "Iterations");
         foreach (var t in tasks)
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              t.Status != TaskStatus.Canceled ? t.Result.ToString("N0") : "n/a");
// The example displays output like the following:
//    Waiting for the first 10 tasks to complete...
//    Status of tasks:
//       Task Id               Status     Iterations
//             1      RanToCompletion      2,000,000
//             2      RanToCompletion      2,000,000
//             3      RanToCompletion      2,000,000
//             4      RanToCompletion      2,000,000
//             5      RanToCompletion      2,000,000
//             6      RanToCompletion      2,000,000
//             7      RanToCompletion      2,000,000
//             8      RanToCompletion      2,000,000
//             9      RanToCompletion      2,000,000
//            10             Canceled            n/a
//            11             Canceled            n/a
//            12             Canceled            n/a
//            13             Canceled            n/a
//            14             Canceled            n/a
//            15             Canceled            n/a
//            16      RanToCompletion      2,000,000
//            17             Canceled            n/a
//            18             Canceled            n/a
//            19             Canceled            n/a
//            20             Canceled            n/a

Instead of using the InnerExceptions property to examine exceptions, the example iterates all tasks to determine which have completed successfully and which have been cancelled. For those that have completed, it displays the value returned by the task.

Because cancellation is cooperative, each task can decide how to respond to cancellation. The following example is like the first, except that, once the token is cancelled, tasks return the number of iterations they've completed rather than throw an exception.

The example still must handle the AggregateException exception, since any tasks that have not started when cancellation is requested still throw an exception.

Universal Windows Platform
Available since 4.5
.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
© 2015 Microsoft