TaskFactory.StartNew Method

Definition

Creates and starts a task.

Overloads

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.

StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler)

Creates and starts a task for the specified action delegate, cancellation token, creation options and state.

StartNew(Action<Object>, Object, TaskCreationOptions)

Creates and starts a task for the specified action delegate, state and creation options.

StartNew(Action<Object>, Object, CancellationToken)

Creates and starts a task for the specified action delegate, state and cancellation token.

StartNew(Action, CancellationToken)

Creates and starts a task for the specified action delegate and cancellation token.

StartNew(Action, TaskCreationOptions)

Creates and starts a task for the specified action delegate and creation options.

StartNew(Action)

Creates and starts a task for the specified action delegate.

StartNew(Action<Object>, Object)

Creates and starts a task for the specified action delegate and state.

StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler)

Creates and starts a task of type TResult for the specified function delegate, cancellation token, creation options and task scheduler.

StartNew<TResult>(Func<TResult>)

Creates and starts a task of type TResult for the specified function delegate.

StartNew<TResult>(Func<Object,TResult>, Object)

Creates and starts a task of type TResult for the specified function delegate and state.

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

Creates and starts a task of type TResult for the specified function delegate and cancellation token.

StartNew<TResult>(Func<TResult>, TaskCreationOptions)

Creates and starts a task of type TResult for the specified function delegate and creation options.

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken)

Creates and starts a task of type TResult for the specified function delegate, state and cancellation token.

StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions)

Creates and starts a task of type TResult for the specified function delegate, state and creation options.

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

Creates and starts a task of type TResult for the specified function delegate, state, cancellation token, creation options and task scheduler.

Remarks

Starting with the .NET Framework 4.5, the Task.Run method is the recommended way to launch a compute-bound task. Use the StartNew method only when you require fine-grained control for a long-running, compute-bound task. This includes scenarios in which you want to control the following:

  • Task creation options. Tasks created by the Task.Run method by default are created with the TaskCreationOptions.DenyChildAttach option. To override this behavior, or to provide other TaskCreationOptions options, call a StartNew overload.

  • Parameter passing. The overloads of the Task.Run method do not allow you to pass a parameter to the task delegate. Overloads of the StartNew method do.

  • The task scheduler. The overloads of the Task.Run method use the default task scheduler. To control the task scheduler, call a StartNew overload with a scheduler parameter. For more information, see TaskScheduler.

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.

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

Parameters

action
Action<Object>

The action delegate to execute asynchronously.

state
Object

An object containing data to be used by the action delegate.

cancellationToken
CancellationToken

The cancellation token that will be assigned to the new task.

creationOptions
TaskCreationOptions

One of the enumeration values that controls the behavior of the created task.

scheduler
TaskScheduler

The task scheduler that is used to schedule the created task.

Returns

The started task.

Exceptions

The provided CancellationToken has already been disposed.

action is null.

-or-

scheduler is null.

creationOptions argument specifies an invalid TaskCreationOptions value. For more information, see the Remarks for FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Remarks

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task for the specified action delegate, cancellation token, creation options and state.

public System.Threading.Tasks.Task StartNew (Action action, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);

Parameters

action
Action

The action delegate to execute asynchronously.

cancellationToken
CancellationToken

The cancellation token that will be assigned to the new task.

creationOptions
TaskCreationOptions

One of the enumeration values that controls the behavior of the created task.

scheduler
TaskScheduler

The task scheduler that is used to schedule the created task.

Returns

The started task.

Exceptions

The provided CancellationToken has already been disposed.

action is null.

-or-

scheduler is null.

creationOptions specifies an invalid TaskCreationOptions value. For more information, see the Remarks for FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

Remarks

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew(Action<Object>, Object, TaskCreationOptions)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task for the specified action delegate, state and creation options.

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

Parameters

action
Action<Object>

The action delegate to execute asynchronously.

state
Object

An object containing data to be used by the action delegate.

creationOptions
TaskCreationOptions

One of the enumeration values that controls the behavior of the created task.

Returns

The started task.

Exceptions

action is null.

creationOptions specifies an invalid TaskCreationOptions value.

Remarks

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew(Action<Object>, Object, CancellationToken)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task for the specified action delegate, state and cancellation token.

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

Parameters

action
Action<Object>

The action delegate to execute asynchronously.

state
Object

An object containing data to be used by the action delegate.

cancellationToken
CancellationToken

The cancellation token that will be assigned to the new task.

Returns

The started task.

Exceptions

The provided CancellationToken has already been disposed.

action is null.

Examples

The following example defines an array of 6-letter words. Each word is then passed to an Action<T> delegate, which scrambles the word and displays the original word and its scrambled version.

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

public class Example
{
   public static void Main()
   {
      CancellationTokenSource cts = new CancellationTokenSource();
      CancellationToken token = cts.Token;
      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)
         tasks.Add(Task.Factory.StartNew( (word) => { Char[] chars = word.ToString().ToCharArray();
                                                      double[] order = new double[chars.Length];
                                                      token.ThrowIfCancellationRequested();
                                                      bool wasZero = false;
                                                      lock (lockObj) {
                                                         for (int ctr = 0; ctr < order.Length; ctr++) {
                                                             order[ctr] = rnd.NextDouble();
                                                             if (order[ctr] == 0) {
                                                                if (! wasZero) {
                                                                   wasZero = true;
                                                                }
                                                                else {
                                                                   cts.Cancel();
                                                                }
                                                             }
                                                         }
                                                      }
                                                      token.ThrowIfCancellationRequested();
                                                      Array.Sort(order, chars);
                                                      Console.WriteLine("{0} --> {1}", word,
                                                                        new String(chars));
                                                    }, word6, token));

      try {
         Task.WaitAll(tasks.ToArray());
      }
      catch (AggregateException e) {
         foreach (var ie in e.InnerExceptions) {
            if (ie is OperationCanceledException) {
               Console.WriteLine("The word scrambling operation has been cancelled.");
               break;
            }
            else {
               Console.WriteLine(ie.GetType().Name + ": " + ie.Message);
            }
         }
      }
      finally {
         cts.Dispose();
      }
   }
}
// The example displays output like the following:
//    regain --> irnaeg
//    ordain --> rioadn
//    reason --> soearn
//    rained --> rinade
//    rioter --> itrore
//    senior --> norise
//    rental --> atnerl
//    editor --> oteird

Note that the example initializes a single random number generator, which is protected by a lock. For the need of a lock, see "The System.Random class and thread safety" in the Random class topic. To handle the possibility of corruption of the random number generator, a cancellation token is passed to task. If two random numbers equal zero, the method assumes that the random number generator is corrupted and sets the cancellation token. Before sorting the chars array that contains the six characters in a word, the method calls the CancellationToken.ThrowIfCancellationRequested method to throw an OperationCanceledException if the token has been canceled.

Remarks

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew(Action, CancellationToken)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task for the specified action delegate and cancellation token.

public System.Threading.Tasks.Task StartNew (Action action, System.Threading.CancellationToken cancellationToken);

Parameters

action
Action

The action delegate to execute asynchronously.

cancellationToken
CancellationToken

The cancellation token that will be assigned to the new task.

Returns

The started task.

Exceptions

The provided CancellationToken has already been disposed.

action is null.

Examples

The following example calls the StartNew(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.Factory.StartNew( () => { 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);       
      }
      finally {
         tokenSource.Dispose();
      }
   }
}
// The example displays the following output:
//       Exception messages:
//          TaskCanceledException: A task was canceled.
//       
//       Task status: Canceled

Remarks

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Task.Run(Action, CancellationToken) method as a quick way to call StartNew(Action, CancellationToken) with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : Task.Run(Action, CancellationToken) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task instance, whereas StartNew(Action, CancellationToken) does. For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew(Action, TaskCreationOptions)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task for the specified action delegate and creation options.

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

Parameters

action
Action

The action delegate to execute asynchronously.

creationOptions
TaskCreationOptions

One of the enumeration values that controls the behavior of the created task.

Returns

The started task.

Exceptions

action is null.

creationOptions specifies an invalid TaskCreationOptions value.

Remarks

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew(Action)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task for the specified action delegate.

public System.Threading.Tasks.Task StartNew (Action action);

Parameters

action
Action

The action delegate to execute asynchronously.

Returns

The started task.

Exceptions

The action argument is null.

Examples

The following example uses the StartNew(Action) method to repeatedly invoke an Action delegate that generates a random number, interprets it as a Unicode code point, converts it to a UTF16-encoded code unit, and displays information about the resulting character or characters.

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

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      List<Task> tasks  = new List<Task>();
      // Execute the task 10 times.
      for (int ctr = 1; ctr <= 9; ctr++) {
         tasks.Add(Task.Factory.StartNew( () => {
                                            int utf32 = 0;
                                            lock(rnd) {
                                               // Get UTF32 value.
                                               utf32 = rnd.Next(0, 0xE01F0);
                                            }
                                            // Convert it to a UTF16-encoded character.
                                            string utf16 = Char.ConvertFromUtf32(utf32);
                                            // Display information about the character.
                                            Console.WriteLine("0x{0:X8} --> '{1,2}' ({2})", 
                                                              utf32, utf16, ShowHex(utf16));
                                         }));                           
      }
      Task.WaitAll(tasks.ToArray()); 
   }

   private static string ShowHex(string value)
   {
      string hexString = null;
      // Handle only non-control characters.
      if (! Char.IsControl(value, 0)) {
         foreach (var ch in value)
            hexString += $"0x{(ushort)ch:X} ";
      }   
      return hexString.Trim();
   }
}
// The example displays the following output:
//       0x00097103 --> '򗄃' (0x55836 0x56579)
//       0x000A98A1 --> '򩢡' (0x55910 0x56481)
//       0x00050002 --> '񐀂' (0x55552 0x56322)
//       0x0000FEF1 --> 'ﻱ' (0x65265)
//       0x0008BC0A --> '򋰊' (0x55791 0x56330)
//       0x000860EA --> '򆃪' (0x55768 0x56554)
//       0x0009AC5A --> '򚱚' (0x55851 0x56410)
//       0x00053320 --> '񓌠' (0x55564 0x57120)
//       0x000874EF --> '򇓯' (0x55773 0x56559)

Remarks

Calling StartNew is functionally equivalent to creating a task by using one of its constructors, and then calling the Task.Start method to schedule the task for execution.

Starting with the .NET Framework 4.5, you can use the Task.Run(Action) method as a quick way to call StartNew(Action) with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : Task.Run(Action) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task instance, whereas StartNew(Action) does. For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew(Action<Object>, Object)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task for the specified action delegate and state.

public System.Threading.Tasks.Task StartNew (Action<object> action, object state);
public System.Threading.Tasks.Task StartNew (Action<object?> action, object? state);

Parameters

action
Action<Object>

The action delegate to execute asynchronously.

state
Object

An object containing data to be used by the action delegate.

Returns

The started task.

Exceptions

The action argument is null.

Examples

The following example defines an array of 6-letter words. Each word is then passed to an Action<T> delegate, which scrambles the word and displays the original word and its scrambled version.

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

public class Example
{
   public static void 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)
         tasks.Add(Task.Factory.StartNew( (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));

      Task.WaitAll(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

Note that the example initializes a single random number generator, which is protected by a lock. For the need of a lock, see "The System.Random class and thread safety" in the Random class topic.

Remarks

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling the Start method to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task of type TResult for the specified function delegate, cancellation token, creation options and task scheduler.

public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);

Type Parameters

TResult

The type of the result available through the task.

Parameters

function
Func<TResult>

A function delegate that returns the future result to be available through the task.

cancellationToken
CancellationToken

The cancellation token that will be assigned to the new task.

creationOptions
TaskCreationOptions

One of the enumeration values that controls the behavior of the created task.

scheduler
TaskScheduler

The task scheduler that is used to schedule the created task.

Returns

The started task.

Exceptions

The provided CancellationToken has already been disposed.

function is null.

-or-

scheduler is null.

Remarks

Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew<TResult>(Func<TResult>)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task of type TResult for the specified function delegate.

public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function);

Type Parameters

TResult

The type of the result available through the task.

Parameters

function
Func<TResult>

A function delegate that returns the future result to be available through the task.

Returns

The started task.

Exceptions

The function argument is null.

Examples

The following example is a simple addition app that generates two random numbers and prompts the user to enter their sum. It then indicates whether the answer is correct or, if the user's response is not a valid number, prompts the user to re-enter a valid number. The StartNew is used to create the Task<TResult> objects that return the random numbers to add.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      Task<int>[] tasks = new Task<int>[2];
      Object obj = new Object();
      
      while (true) {
         for (int ctr = 0; ctr <= 1; ctr++)
            tasks[ctr] = Task.Factory.StartNew(() => { int i = 0;
                                                       lock(obj) {
                                                          i = rnd.Next(101);
                                                       }
                                                       return i; });

         Task.WaitAll(tasks);
         int n1 = tasks[0].Result;
         int n2 = tasks[1].Result;
         int result = n1 + n2;
         bool validInput = false;
         while (! validInput) {
            ShowMessage(n1, n2);
            string userInput = Console.ReadLine();
            // Process user input.
            if (userInput.Trim().ToUpper() == "X") return;
            int answer;
            validInput = Int32.TryParse(userInput, out answer);
            if (! validInput)
               Console.WriteLine("Invalid input. Try again, but enter only numbers. ");
            else if (answer == result)
               Console.WriteLine("Correct!");
            else
               Console.WriteLine("Incorrect. The correct answer is {0}.", result);
         }
      }
   }

   private static void ShowMessage(int n1, int n2)
   {
      Console.WriteLine("\nEnter 'x' to exit...");
      Console.Write("{0} + {1} = ", n1, n2);
   }
}
// The example displays the following output:
//       Enter 'x' to exit...
//       15 + 11 = 26
//       Correct!
//
//       Enter 'x' to exit...
//       75 + 33 = adc
//       Invalid input. Try again, but enter only numbers.
//
//       Enter 'x' to exit...
//       75 + 33 = 108
//       Correct!
//
//       Enter 'x' to exit...
//       67 + 55 = 133
//       Incorrect. The correct answer is 122.
//
//       Enter 'x' to exit...
//       92 + 51 = 133
//       Incorrect. The correct answer is 143.
//
//       Enter 'x' to exit...
//       81 + 65 = x

Remarks

Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can call the Task.Run<TResult>(Func<TResult>) method as a quick way to call StartNew with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : Task.Run<TResult>(Func<TResult>) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task<TResult> instance, whereas StartNew<TResult>(Func<TResult>) does. For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew<TResult>(Func<Object,TResult>, Object)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task of type TResult for the specified function delegate and state.

public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object?,TResult> function, object? state);

Type Parameters

TResult

The type of the result available through the task.

Parameters

function
Func<Object,TResult>

A function delegate that returns the future result to be available through the task.

state
Object

An object containing data to be used by the function delegate.

Returns

The started task.

Exceptions

function is null.

Remarks

Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

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

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task of type TResult for the specified function delegate and cancellation token.

public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function, System.Threading.CancellationToken cancellationToken);

Type Parameters

TResult

The type of the result available through the task.

Parameters

function
Func<TResult>

A function delegate that returns the future result to be available through the task.

cancellationToken
CancellationToken

The cancellation token that will be assigned to the new task.

Returns

The started task.

Exceptions

The provided CancellationToken has already been disposed.

function is null.

Examples

The following example uses two tasks to compute the Fibonacci sequence ending in F100 = F100-1 + F100-2 with seed values F1= 1, F2 = 1 and F1 = 0, F2= 1. Approximately half of the time, a cancellation token is set as the operations execute. The output from the example shows the result if the two tasks complete successfully and if the token is cancelled.

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

public class Example
{
   public static void Main()
   {
      var rnd = new Random();
      var tasks = new List<Task<BigInteger[]>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      for (int ctr = 0; ctr <= 1; ctr++) {
         int start = ctr;
         tasks.Add(Task.Run( () => { BigInteger[] sequence = new BigInteger[100];
                                     sequence[0] = start;
                                     sequence[1] = 1;
                                     for (int index = 2; index <= sequence.GetUpperBound(0); index++) {
                                        token.ThrowIfCancellationRequested();
                                        sequence[index] = sequence[index - 1] + sequence[index - 2];
                                     }
                                     return sequence;
                                   }, token));
      }
      if (rnd.Next(0, 2) == 1)
         source.Cancel();
      try {
         Task.WaitAll(tasks.ToArray());
         foreach (var t in tasks)
            Console.WriteLine("{0}, {1}...{2:N0}", t.Result[0], t.Result[1],
                              t.Result[99]);
      }
      catch (AggregateException e) {
         foreach (var ex in e.InnerExceptions)
            Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message);
      }
   }
}
// The example displays either the following output:
//    0, 1...218,922,995,834,555,169,026
//    1, 1...354,224,848,179,261,915,075
// or the following output:
//    TaskCanceledException: A task was canceled.
//    TaskCanceledException: A task was canceled.

Remarks

Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Task.Run<TResult>(Func<TResult>, CancellationToken) method as a quick way to call StartNew<TResult>(Func<TResult>, CancellationToken) with default parameters. Note, however, that there is a difference in behavior between the two methods regarding : Task.Run<TResult>(Func<TResult>, CancellationToken) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task<TResult> instance, whereas StartNew<TResult>(Func<TResult>, CancellationToken) does. For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew<TResult>(Func<TResult>, TaskCreationOptions)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task of type TResult for the specified function delegate and creation options.

public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function, System.Threading.Tasks.TaskCreationOptions creationOptions);

Type Parameters

TResult

The type of the result available through the task.

Parameters

function
Func<TResult>

A function delegate that returns the future result to be available through the task.

creationOptions
TaskCreationOptions

One of the enumeration values that controls the behavior of the created task.

Returns

The started task.

Exceptions

function is null.

Remarks

Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task of type TResult for the specified function delegate, state and cancellation token.

public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state, System.Threading.CancellationToken cancellationToken);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object?,TResult> function, object? state, System.Threading.CancellationToken cancellationToken);

Type Parameters

TResult

The type of the result available through the task.

Parameters

function
Func<Object,TResult>

A function delegate that returns the future result to be available through the task.

state
Object

An object containing data to be used by the function delegate.

cancellationToken
CancellationToken

The cancellation token that will be assigned to the new task.

Returns

The started task.

Exceptions

The provided CancellationToken has already been disposed.

function is null.

Remarks

Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task of type TResult for the specified function delegate, state and creation options.

public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object?,TResult> function, object? state, System.Threading.Tasks.TaskCreationOptions creationOptions);

Type Parameters

TResult

The type of the result available through the task.

Parameters

function
Func<Object,TResult>

A function delegate that returns the future result to be available through the task.

state
Object

An object containing data to be used by the function delegate.

creationOptions
TaskCreationOptions

One of the enumeration values that controls the behavior of the created task.

Returns

The started task.

Exceptions

function is null.

Remarks

Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

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

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

Source:
TaskFactory.cs
Source:
TaskFactory.cs
Source:
TaskFactory.cs

Creates and starts a task of type TResult for the specified function delegate, state, cancellation token, creation options and task scheduler.

public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object?,TResult> function, object? state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);

Type Parameters

TResult

The type of the result available through the task.

Parameters

function
Func<Object,TResult>

A function delegate that returns the future result to be available through the task.

state
Object

An object containing data to be used by the function delegate.

cancellationToken
CancellationToken

The cancellation token that will be assigned to the new task.

creationOptions
TaskCreationOptions

One of the enumeration values that controls the behavior of the created task.

scheduler
TaskScheduler

The task scheduler that is used to schedule the created task.

Returns

The started task.

Exceptions

The provided CancellationToken has already been disposed.

function is null.

-or-

scheduler is null.

Remarks

Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

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