Task Constructors

Definition

Initializes a new Task.

Overloads

Task(Action)

Initializes a new Task with the specified action.

Task(Action, CancellationToken)

Initializes a new Task with the specified action and CancellationToken.

Task(Action, TaskCreationOptions)

Initializes a new Task with the specified action and creation options.

Task(Action<Object>, Object)

Initializes a new Task with the specified action and state.

Task(Action, CancellationToken, TaskCreationOptions)

Initializes a new Task with the specified action and creation options.

Task(Action<Object>, Object, CancellationToken)

Initializes a new Task with the specified action, state, and CancellationToken.

Task(Action<Object>, Object, TaskCreationOptions)

Initializes a new Task with the specified action, state, and options.

Task(Action<Object>, Object, CancellationToken, TaskCreationOptions)

Initializes a new Task with the specified action, state, and options.

Task(Action)

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

Initializes a new Task with the specified action.

C#
public Task(Action action);

Parameters

action
Action

The delegate that represents the code to execute in the task.

Exceptions

The action argument is null.

Examples

The following example uses the Task(Action) constructor to create tasks that retrieve the filenames in specified directories. 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 async Task Main()
   {
      var list = new ConcurrentBag<string>();
      string[] dirNames = { ".", ".." };
      List<Task> tasks = new List<Task>();
      foreach (var dirName in dirNames) {
         Task t = new Task( () => { foreach(var path in Directory.GetFiles(dirName))
                                    list.Add(path); }  );
         tasks.Add(t);
         t.Start();
      }
      await Task.WhenAll(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

The following example is identical, except that it used the Run(Action) method to instantiate and run the task in a single operation. The method returns the Task object that represents the task.

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

This constructor should only be used in advanced scenarios where it is required that the creation and starting of the task is separated.

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static Task.Run(Action) or TaskFactory.StartNew(Action) method.

If a task with no action is needed just for the consumer of an API to have something to await, a TaskCompletionSource<TResult> should be used.

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

Task(Action, CancellationToken)

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

Initializes a new Task with the specified action and CancellationToken.

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

Parameters

action
Action

The delegate that represents the code to execute in the task.

cancellationToken
CancellationToken

The CancellationToken that the new task will observe.

Exceptions

The provided CancellationToken has already been disposed.

The action argument is null.

Examples

The following example calls the Task(Action, CancellationToken) constructor 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. The Start method is then called to start the task.

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 = new Task(() => { 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);
      t.Start();
      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.
//       
//       Task status: Canceled

Remarks

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static Task.Run(Action, CancellationToken) and TaskFactory.StartNew(Action, CancellationToken) methods. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

For more information, see Task Parallelism (Task Parallel Library) and Cancellation in Managed Threads.

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

Task(Action, TaskCreationOptions)

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

Initializes a new Task with the specified action and creation options.

C#
public Task(Action action, System.Threading.Tasks.TaskCreationOptions creationOptions);

Parameters

action
Action

The delegate that represents the code to execute in the task.

creationOptions
TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

The action argument is null.

The creationOptions argument specifies an invalid value for TaskCreationOptions.

Remarks

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action, TaskCreationOptions) method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

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

Task(Action<Object>, Object)

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

Initializes a new Task with the specified action and state.

C#
public Task(Action<object> action, object state);
C#
public Task(Action<object?> action, object? state);

Parameters

action
Action<Object>

The delegate that represents the code to execute in the task.

state
Object

An object representing data to be used by the action.

Exceptions

The action argument is null.

Examples

The following example defines an array of 6-letter words. Each word is then passed as an argument to the Task(Action<Object>, Object) constructor, whose Action<T> delegate scrambles the characters in the word, then displays the original word and its scrambled version.

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

public class Example
{
   public static async Task Main()
   {
      var tasks = new List<Task>();
      Random rnd = new Random();
      Object lockObj = new Object();
      String[] words6 = { "reason", "editor", "rioter", "rental",
                          "senior", "regain", "ordain", "rained" };

      foreach (var word6 in words6) {
         Task t = new Task( (word) => { Char[] chars = word.ToString().ToCharArray();
                                        double[] order = new double[chars.Length];
                                        lock (lockObj) {
                                           for (int ctr = 0; ctr < order.Length; ctr++)
                                              order[ctr] = rnd.NextDouble();
                                           }
                                        Array.Sort(order, chars);
                                        Console.WriteLine("{0} --> {1}", word,
                                                          new String(chars));
                                      }, word6);
         t.Start();
         tasks.Add(t);
      }
      await Task.WhenAll(tasks.ToArray());
   }
}
// The example displays output like the following:
//    regain --> irnaeg
//    ordain --> rioadn
//    reason --> soearn
//    rained --> rinade
//    rioter --> itrore
//    senior --> norise
//    rental --> atnerl
//    editor --> oteird

Remarks

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action<Object>, Object) method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

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

Task(Action, CancellationToken, TaskCreationOptions)

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

Initializes a new Task with the specified action and creation options.

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

Parameters

action
Action

The delegate that represents the code to execute in the task.

cancellationToken
CancellationToken

The CancellationToken that the new task will observe.

creationOptions
TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

The action argument is null.

The creationOptions argument specifies an invalid value for TaskCreationOptions.

Remarks

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

For more information, see Task Parallelism (Task Parallel Library) and Task Cancellation.

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

Task(Action<Object>, Object, CancellationToken)

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

Initializes a new Task with the specified action, state, and CancellationToken.

C#
public Task(Action<object> action, object state, System.Threading.CancellationToken cancellationToken);
C#
public Task(Action<object?> action, object? state, System.Threading.CancellationToken cancellationToken);

Parameters

action
Action<Object>

The delegate that represents the code to execute in the task.

state
Object

An object representing data to be used by the action.

cancellationToken
CancellationToken

The CancellationToken that the new task will observe.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

The action argument is null.

Remarks

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action<Object>, Object, CancellationToken) method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

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

Task(Action<Object>, Object, TaskCreationOptions)

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

Initializes a new Task with the specified action, state, and options.

C#
public Task(Action<object> action, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
C#
public Task(Action<object?> action, object? state, System.Threading.Tasks.TaskCreationOptions creationOptions);

Parameters

action
Action<Object>

The delegate that represents the code to execute in the task.

state
Object

An object representing data to be used by the action.

creationOptions
TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

The action argument is null.

The creationOptions argument specifies an invalid value for TaskCreationOptions.

Remarks

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action<Object>, Object, TaskCreationOptions) method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

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

Task(Action<Object>, Object, CancellationToken, TaskCreationOptions)

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

Initializes a new Task with the specified action, state, and options.

C#
public Task(Action<object> action, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
C#
public Task(Action<object?> action, object? state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);

Parameters

action
Action<Object>

The delegate that represents the code to execute in the task.

state
Object

An object representing data to be used by the action.

cancellationToken
CancellationToken

The CancellationToken that the new task will observe.

creationOptions
TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

The action argument is null.

The creationOptions argument specifies an invalid value for TaskCreationOptions.

Remarks

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

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