Task<TResult> Task<TResult> Task<TResult> Constructors

Definition

Overloads

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

Initializes a new Task<TResult> with the specified function.

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

Initializes a new Task<TResult> with the specified function and state.

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

Initializes a new Task<TResult> with the specified function.

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

Initializes a new Task<TResult> with the specified function and creation options.

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

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

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

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

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

Initializes a new Task<TResult> with the specified function and creation options.

Task<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions) Task<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions)

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

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

Initializes a new Task<TResult> with the specified function.

public:
 Task(Func<TResult> ^ function);
public Task (Func<TResult> function);
Public Sub New (function As Func(Of TResult))
Parameters
function
Func<TResult> Func<TResult> Func<TResult>

The delegate that represents the code to execute in the task. When the function has completed, the task's Result property will be set to return the result value of the function.

Exceptions

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 Task.WaitAll(Task[]) method is called to ensure that all tasks have completed before displaying the word count of each book to the console.

Object instantiation is separated from object execution in this example so that the example can ensure that each file exists. If they do not, it displays the name of the missing file. Otherwise, it calls the Task.Start method to launch each task.

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] = new Task<int>( () => {
                                   // Number of words.
                                   int nWords = 0;
                                   // Create filename from title.
                                   string fn = s + ".txt";

                                   StreamReader sr = new StreamReader(fn);
                                   string input = sr.ReadToEndAsync().Result;
                                   sr.Close();
                                   nWords = Regex.Matches(input, pattern).Count;
                                   return nWords;
                                } );
      }
      // Ensure files exist before launching tasks.
      bool allExist = true;
      foreach (var title in titles) {
         string fn = title + ".txt";
         if (! File.Exists(fn)) {
            allExist = false;
            Console.WriteLine("Cannot find '{0}'", fn);
            break;
         }   
      }
      // Launch tasks 
      if (allExist) {
         foreach (var t in tasks)
            t.Start();
      
        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
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim pattern As String = "\p{P}*\s+"
      Dim titles() As String = { "Sister Carrie",
                                 "The Financier" }
      Dim tasks(titles.Length - 1) As Task(Of Integer)

      For ctr As Integer = 0 To titles.Length - 1
         Dim s As String = titles(ctr)
         tasks(ctr) = New Task(Of Integer)( Function()
                                   ' Number of words.
                                   Dim nWords As Integer = 0
                                   ' Create filename from title.
                                   Dim fn As String = s + ".txt"

                                   Dim sr As New StreamReader(fn)
                                   Dim input As String = sr.ReadToEndAsync().Result
                                   sr.Close()
                                   nWords = Regex.Matches(input, pattern).Count
                                   Return nWords
                                End Function)
      Next

      ' Ensure files exist before launching tasks.
      Dim allExist As Boolean = True
      For Each title In titles
         Dim fn As String = title + ".txt"
         If Not File.Exists(fn) Then
            allExist = false
            Console.WriteLine("Cannot find '{0}'", fn)
            Exit For
         End If   
      Next
      ' Launch tasks 
      If allExist Then
         For Each t in tasks
            t.Start()
         Next
         Task.WaitAll(tasks)

         Console.WriteLine("Word Counts:")
         Console.WriteLine()
         For ctr As Integer = 0 To titles.Length - 1
         Console.WriteLine("{0}: {1,10:N0} words", titles(ctr), tasks(ctr).Result)
         Next
      End If   
   End Sub
End Module
' The example displays the following output:
'       Sister Carrie:    159,374 words
'       The Financier:    196,362 words

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

Remarks

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

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

Initializes a new Task<TResult> with the specified function and state.

public:
 Task(Func<System::Object ^, TResult> ^ function, System::Object ^ state);
public Task (Func<object,TResult> function, object state);
Public Sub New (function As Func(Of Object, TResult), state As Object)
Parameters
function
Func<Object,TResult>

The delegate that represents the code to execute in the task. When the function has completed, the task's Result property will be set to return the result value of the function.

state
Object Object Object

An object representing data to be used by the action.

Exceptions

Remarks

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

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

Initializes a new Task<TResult> with the specified function.

public:
 Task(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken);
public Task (Func<TResult> function, System.Threading.CancellationToken cancellationToken);
Parameters
function
Func<TResult> Func<TResult> Func<TResult>

The delegate that represents the code to execute in the task. When the function has completed, the task's Result property will be set to return the result value of the function.

cancellationToken
CancellationToken CancellationToken CancellationToken

The CancellationToken to be assigned to this task.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

Remarks

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

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

Initializes a new Task<TResult> with the specified function and creation options.

public:
 Task(Func<TResult> ^ function, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Func<TResult> function, System.Threading.Tasks.TaskCreationOptions creationOptions);
Public Sub New (function As Func(Of TResult), creationOptions As TaskCreationOptions)
Parameters
function
Func<TResult> Func<TResult> Func<TResult>

The delegate that represents the code to execute in the task. When the function has completed, the task's Result property will be set to return the result value of the function.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

Remarks

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

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

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

public:
 Task(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::CancellationToken cancellationToken);
public Task (Func<object,TResult> function, object state, System.Threading.CancellationToken cancellationToken);
Parameters
function
Func<Object,TResult>

The delegate that represents the code to execute in the task. When the function has completed, the task's Result property will be set to return the result value of the function.

state
Object Object Object

An object representing data to be used by the function.

cancellationToken
CancellationToken CancellationToken CancellationToken

The CancellationToken to be assigned to the new task.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

Remarks

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

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

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

public:
 Task(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Func<object,TResult> function, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
Public Sub New (function As Func(Of Object, TResult), state As Object, creationOptions As TaskCreationOptions)
Parameters
function
Func<Object,TResult>

The delegate that represents the code to execute in the task. When the function has completed, the task's Result property will be set to return the result value of the function.

state
Object Object Object

An object representing data to be used by the function.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

Remarks

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

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

Initializes a new Task<TResult> with the specified function and creation options.

public:
 Task(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Func<TResult> function, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
Parameters
function
Func<TResult> Func<TResult> Func<TResult>

The delegate that represents the code to execute in the task. When the function has completed, the task's Result property will be set to return the result value of the function.

cancellationToken
CancellationToken CancellationToken CancellationToken

The CancellationToken that will be assigned to the new task.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

Remarks

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

Task<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions) Task<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions)

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

public:
 Task(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Func<object,TResult> function, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
Parameters
function
Func<Object,TResult>

The delegate that represents the code to execute in the task. When the function has completed, the task's Result property will be set to return the result value of the function.

state
Object Object Object

An object representing data to be used by the function.

cancellationToken
CancellationToken CancellationToken CancellationToken

The CancellationToken to be assigned to the new task.

creationOptions
TaskCreationOptions TaskCreationOptions TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

Remarks

Rather than calling this constructor, the most common way to instantiate a Task<TResult> object and launch a task is by calling the static TaskFactory<TResult>.StartNew(Func<Object,TResult>, 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