Bearbeiten

Teilen über


Task<TResult> Constructors

Definition

Initializes a new Task<TResult> object.

Overloads

Task<TResult>(Func<TResult>)

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

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

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

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

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

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

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

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)

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

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)

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

Task<TResult>(Func<TResult>)

Source:
Future.cs
Source:
Future.cs
Source:
Future.cs

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

public:
 Task(Func<TResult> ^ function);
public Task (Func<TResult> function);
new System.Threading.Tasks.Task<'Result> : Func<'Result> -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of TResult))

Parameters

function
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

The function argument is null.

The function argument 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 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 async Task 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();
      
        await Task.WhenAll(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 white-space characters. It assumes that the total number of matches equals the approximate word count.

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<TResult> object and launch a task is by calling the static Task.Run<TResult>(Func<TResult>) and TaskFactory<TResult>.StartNew(Func<TResult>) methods.

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

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

Source:
Future.cs
Source:
Future.cs
Source:
Future.cs

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 Task (Func<object?,TResult> function, object? state);
new System.Threading.Tasks.Task<'Result> : Func<obj, 'Result> * obj -> System.Threading.Tasks.Task<'Result>
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

An object representing data to be used by the action.

Exceptions

The function argument is null.

The function argument is null.

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.

See also

Applies to

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

Source:
Future.cs
Source:
Future.cs
Source:
Future.cs

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);
new System.Threading.Tasks.Task<'Result> : Func<'Result> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of TResult), cancellationToken As CancellationToken)

Parameters

function
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

The CancellationToken to be assigned to this task.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

The function argument is null.

The function argument is null.

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.

See also

Applies to

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

Source:
Future.cs
Source:
Future.cs
Source:
Future.cs

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);
new System.Threading.Tasks.Task<'Result> : Func<'Result> * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of TResult), creationOptions As TaskCreationOptions)

Parameters

function
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

The TaskCreationOptions used to customize the task's behavior.

Exceptions

The creationOptions argument specifies an invalid value for TaskCreationOptions.

The function argument is null.

The function argument is null.

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.

See also

Applies to

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

Source:
Future.cs
Source:
Future.cs
Source:
Future.cs

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);
public Task (Func<object?,TResult> function, object? state, System.Threading.CancellationToken cancellationToken);
new System.Threading.Tasks.Task<'Result> : Func<obj, 'Result> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of Object, TResult), state As Object, cancellationToken As 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

An object representing data to be used by the function.

cancellationToken
CancellationToken

The CancellationToken to be assigned to the new task.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

The function argument is null.

The function argument is null.

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.

See also

Applies to

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

Source:
Future.cs
Source:
Future.cs
Source:
Future.cs

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 Task (Func<object?,TResult> function, object? state, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task<'Result> : Func<obj, 'Result> * obj * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
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

An object representing data to be used by the function.

creationOptions
TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

The creationOptions argument specifies an invalid value for TaskCreationOptions.

The function argument is null.

The function argument is null.

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.

See also

Applies to

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

Source:
Future.cs
Source:
Future.cs
Source:
Future.cs

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);
new System.Threading.Tasks.Task<'Result> : Func<'Result> * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of TResult), cancellationToken As CancellationToken, creationOptions As TaskCreationOptions)

Parameters

function
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

The CancellationToken that will be assigned to the new task.

creationOptions
TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

The creationOptions argument specifies an invalid value for TaskCreationOptions.

The function argument is null.

The function argument is null.

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.

See also

Applies to

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

Source:
Future.cs
Source:
Future.cs
Source:
Future.cs

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);
public Task (Func<object?,TResult> function, object? state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task<'Result> : Func<obj, 'Result> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of Object, TResult), state As Object, cancellationToken As CancellationToken, 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

An object representing data to be used by the function.

cancellationToken
CancellationToken

The CancellationToken to be assigned to the new task.

creationOptions
TaskCreationOptions

The TaskCreationOptions used to customize the task's behavior.

Exceptions

The CancellationTokenSource that created cancellationToken has already been disposed.

The creationOptions argument specifies an invalid value for TaskCreationOptions.

The function argument is null.

The function argument is null.

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.

See also

Applies to