Task.Run Method

Definition

Queues the specified work to run on the ThreadPool and returns a task or Task<TResult> handle for that work.

Overloads

Run(Func<Task>, CancellationToken)

Queues the specified work to run on the thread pool and returns a proxy for the task returned by function. A cancellation token allows the work to be cancelled if it has not yet started.

Run(Action, CancellationToken)

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 if it has not yet started.

Run(Func<Task>)

Queues the specified work to run on the thread pool and returns a proxy for the task returned by function.

Run(Action)

Queues the specified work to run on the thread pool and returns a Task object that represents that work.

Run<TResult>(Func<Task<TResult>>)

Queues the specified work to run on the thread pool and returns a proxy for the Task(TResult) returned by function. A cancellation token allows the work to be cancelled if it has not yet started.

Run<TResult>(Func<TResult>)

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 if it has not yet started.

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

Queues the specified work to run on the thread pool and returns a proxy for the Task(TResult) returned by function.

Run<TResult>(Func<TResult>, CancellationToken)

Queues the specified work to run on the thread pool and returns a Task(TResult) object that represents that work.

Remarks

The Run method provides a set of overloads that make it easy to start a task by using default values. It is a lightweight alternative to the StartNew overloads.

Run(Func<Task>, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Queues the specified work to run on the thread pool and returns a proxy for the task returned by function. A cancellation token allows the work to be cancelled if it has not yet started.

C#
public static System.Threading.Tasks.Task Run(Func<System.Threading.Tasks.Task> function, System.Threading.CancellationToken cancellationToken);
C#
public static System.Threading.Tasks.Task Run(Func<System.Threading.Tasks.Task?> function, System.Threading.CancellationToken cancellationToken);

Parameters

function
Func<Task>

The work to execute asynchronously.

cancellationToken
CancellationToken

A cancellation token that can be used to cancel the work if it has not yet started. Run(Func<Task>, CancellationToken) does not pass cancellationToken to action.

Returns

A task that represents a proxy for the task returned by function.

Exceptions

The function parameter was null.

The task has been canceled. This exception is stored into the returned task.

The CancellationTokenSource associated with cancellationToken was disposed.

The task has been canceled.

Remarks

For information on handling exceptions thrown by task operations, see Exception Handling.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Run(Action, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

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 if it has not yet started.

C#
public static System.Threading.Tasks.Task Run(Action action, System.Threading.CancellationToken cancellationToken);

Parameters

action
Action

The work to execute asynchronously.

cancellationToken
CancellationToken

A cancellation token that can be used to cancel the work if it has not yet started. Run(Action, CancellationToken) does not pass cancellationToken to action.

Returns

A task that represents the work queued to execute in the thread pool.

Exceptions

The action parameter was null.

The task has been canceled. This exception is stored into the returned task.

The CancellationTokenSource associated with cancellationToken was disposed.

The task has been canceled.

Examples

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.

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

public class Example
{
   public static async Task 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);
      await Task.Yield();
      tokenSource.Cancel();
      try {
         await t;
         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 {
         tokenSource.Dispose();
      }
   }
}
// The example displays the following output:
//       Exception messages:
//          TaskCanceledException: A task was canceled.
//          TaskCanceledException: A task was canceled.
//          ...
//       
//       Task status: Canceled

Remarks

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.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Run(Func<Task>)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Queues the specified work to run on the thread pool and returns a proxy for the task returned by function.

C#
public static System.Threading.Tasks.Task Run(Func<System.Threading.Tasks.Task> function);
C#
public static System.Threading.Tasks.Task Run(Func<System.Threading.Tasks.Task?> function);

Parameters

function
Func<Task>

The work to execute asynchronously.

Returns

A task that represents a proxy for the task returned by function.

Exceptions

The function parameter was null.

Remarks

For information on handling exceptions thrown by task operations, see Exception Handling.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Run(Action)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Queues the specified work to run on the thread pool and returns a Task object that represents that work.

C#
public static System.Threading.Tasks.Task Run(Action action);

Parameters

action
Action

The work to execute asynchronously.

Returns

A task that represents the work queued to execute in the ThreadPool.

Exceptions

The action parameter was null.

Examples

The following example defines a ShowThreadInfo method that displays the Thread.ManagedThreadId of the current thread. It is called directly from the application thread, and is called from the Action delegate passed to the Run(Action) method.

C#
using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      ShowThreadInfo("Application");

      var t = Task.Run(() => ShowThreadInfo("Task") );
      t.Wait();
   }

   static void ShowThreadInfo(String s)
   {
      Console.WriteLine("{0} thread ID: {1}",
                        s, Thread.CurrentThread.ManagedThreadId);
   }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3

The following example is similar to the previous one, except that it uses a lambda expression to define the code that the task is to execute.

C#
using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("Application thread ID: {0}",
                        Thread.CurrentThread.ManagedThreadId);
      var t = Task.Run(() => {  Console.WriteLine("Task thread ID: {0}",
                                   Thread.CurrentThread.ManagedThreadId);
                             } );
      t.Wait();
   }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3

The examples show that the asynchronous task executes on a different thread than the main application thread.

The call to the Wait method ensures that the task completes and displays its output before the application ends. Otherwise, it is possible that the Main method will complete before the task finishes.

The following example illustrates the Run(Action) method. It defines an array of directory names and starts a separate task to retrieve the file names in each directory. All tasks write the file names to a single ConcurrentBag<T> object. The example then calls the WaitAll(Task[]) method to ensure that all tasks have completed, and then displays a count of the total number of file names written to the ConcurrentBag<T> object.

C#
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var list = new ConcurrentBag<string>();
      string[] dirNames = { ".", ".." };
      List<Task> tasks = new List<Task>();
      foreach (var dirName in dirNames) {
         Task t = Task.Run( () => { foreach(var path in Directory.GetFiles(dirName)) 
                                       list.Add(path); }  );
         tasks.Add(t);
      }
      Task.WaitAll(tasks.ToArray());
      foreach (Task t in tasks)
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status);
         
      Console.WriteLine("Number of files read: {0}", list.Count);
   }
}
// The example displays output like the following:
//       Task 1 Status: RanToCompletion
//       Task 2 Status: RanToCompletion
//       Number of files read: 23

Remarks

The Run method allows you to create and execute a task in a single method call and 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.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Run<TResult>(Func<Task<TResult>>)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Queues the specified work to run on the thread pool and returns a proxy for the Task(TResult) returned by function. A cancellation token allows the work to be cancelled if it has not yet started.

C#
public static System.Threading.Tasks.Task<TResult> Run<TResult>(Func<System.Threading.Tasks.Task<TResult>> function);
C#
public static System.Threading.Tasks.Task<TResult> Run<TResult>(Func<System.Threading.Tasks.Task<TResult>?> function);

Type Parameters

TResult

The type of the result returned by the proxy task.

Parameters

function
Func<Task<TResult>>

The work to execute asynchronously.

Returns

A Task(TResult) that represents a proxy for the Task(TResult) returned by function.

Exceptions

The function parameter was null.

Remarks

For information on handling exceptions thrown by task operations, see Exception Handling.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Run<TResult>(Func<TResult>)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

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 if it has not yet started.

C#
public static System.Threading.Tasks.Task<TResult> Run<TResult>(Func<TResult> function);

Type Parameters

TResult

The return type of the task.

Parameters

function
Func<TResult>

The work to execute asynchronously.

Returns

A task object that represents the work queued to execute in the thread pool.

Exceptions

The function parameter is null.

Examples

The following example counts the approximate number of words in text files that represent published books. Each task is responsible for opening a file, reading its entire contents asynchronously, and calculating the word count by using a regular expression. The WaitAll(Task[]) method is called to ensure that all tasks have completed before displaying the word count of each book to the console.

C#
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      string pattern = @"\p{P}*\s+";
      string[] titles = { "Sister Carrie", "The Financier" };
      Task<int>[] tasks = new Task<int>[titles.Length];

      for (int ctr = 0; ctr < titles.Length; ctr++) {
         string s = titles[ctr];
         tasks[ctr] = Task.Run( () => {
                                   // Number of words.
                                   int nWords = 0;
                                   // Create filename from title.
                                   string fn = s + ".txt";
                                   if (File.Exists(fn)) {
                                      StreamReader sr = new StreamReader(fn);
                                      string input = sr.ReadToEndAsync().Result;
                                      nWords = Regex.Matches(input, pattern).Count;
                                   }
                                   return nWords;
                                } );
      }
      Task.WaitAll(tasks);

      Console.WriteLine("Word Counts:\n");
      for (int ctr = 0; ctr < titles.Length; ctr++)
         Console.WriteLine("{0}: {1,10:N0} words", titles[ctr], tasks[ctr].Result);
   }
}
// The example displays the following output:
//       Sister Carrie:    159,374 words
//       The Financier:    196,362 words

The regular expression \p{P}*\s+ matches zero, one, or more punctuation characters followed by one or more white-space characters. It assumes that the total number of matches equals the approximate word count.

Remarks

The Run method is a simpler alternative to the TaskFactory.StartNew(Action) method. It creates a task with the following default values:

For information on handling exceptions thrown by task operations, see Exception Handling.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

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

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Queues the specified work to run on the thread pool and returns a proxy for the Task(TResult) returned by function.

C#
public static System.Threading.Tasks.Task<TResult> Run<TResult>(Func<System.Threading.Tasks.Task<TResult>> function, System.Threading.CancellationToken cancellationToken);
C#
public static System.Threading.Tasks.Task<TResult> Run<TResult>(Func<System.Threading.Tasks.Task<TResult>?> function, System.Threading.CancellationToken cancellationToken);

Type Parameters

TResult

The type of the result returned by the proxy task.

Parameters

function
Func<Task<TResult>>

The work to execute asynchronously.

cancellationToken
CancellationToken

A cancellation token that can be used to cancel the work if it has not yet started. Run<TResult>(Func<Task<TResult>>, CancellationToken) does not pass cancellationToken to action.

Returns

A Task(TResult) that represents a proxy for the Task(TResult) returned by function.

Exceptions

The function parameter was null.

The task has been canceled. This exception is stored into the returned task.

The CancellationTokenSource associated with cancellationToken was disposed.

The task has been canceled.

Remarks

For information on handling exceptions thrown by task operations, see Exception Handling.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Run<TResult>(Func<TResult>, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Queues the specified work to run on the thread pool and returns a Task(TResult) object that represents that work.

C#
public static System.Threading.Tasks.Task<TResult> Run<TResult>(Func<TResult> function, System.Threading.CancellationToken cancellationToken);

Type Parameters

TResult

The result type of the task.

Parameters

function
Func<TResult>

The work to execute asynchronously.

cancellationToken
CancellationToken

A cancellation token that can be used to cancel the work if it has not yet started. Run<TResult>(Func<TResult>, CancellationToken) does not pass cancellationToken to action.

Returns

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

Exceptions

The function parameter is null.

The task has been canceled. This exception is stored into the returned task.

The CancellationTokenSource associated with cancellationToken was disposed.

The task has been canceled.

Examples

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.

C#
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++) {
                                         token.ThrowIfCancellationRequested();
                                         iterations++;
                                     }
                                     Interlocked.Increment(ref completedIterations);
                                     if (completedIterations >= 10)
                                        source.Cancel();
                                     return iterations; }, token));

      Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
      try  {
         Task.WaitAll(tasks.ToArray());
      }
      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.

C#
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++) {
                                         if (token.IsCancellationRequested)
                                            return iterations;
                                         iterations++;
                                     }
                                     Interlocked.Increment(ref completedIterations);
                                     if (completedIterations >= 10)
                                        source.Cancel();
                                     return iterations; }, token));

      Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
      try  {
         Task.WaitAll(tasks.ToArray());
      }
      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:
//    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      RanToCompletion      1,658,326
//            11      RanToCompletion      1,988,506
//            12      RanToCompletion      2,000,000
//            13      RanToCompletion      1,942,246
//            14      RanToCompletion        950,108
//            15      RanToCompletion      1,837,832
//            16      RanToCompletion      1,687,182
//            17      RanToCompletion        194,548
//            18             Canceled    Not Started
//            19             Canceled    Not Started
//            20             Canceled    Not Started

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

Remarks

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0