Task<TResult> 建構函式

定義

初始化新的 Task<TResult> 物件。Initializes a new Task<TResult> object.

多載

Task<TResult>(Func<TResult>)

使用指定的函式,初始化新的 Task<TResult>Initializes a new Task<TResult> with the specified function.

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

使用指定的函式和狀態,初始化新的 Task<TResult>Initializes a new Task<TResult> with the specified function and state.

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

使用指定的函式,初始化新的 Task<TResult>Initializes a new Task<TResult> with the specified function.

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

使用指定的函式和建立選項,初始化新的 Task<TResult>Initializes a new Task<TResult> with the specified function and creation options.

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

使用指定的動作、狀態和選項,初始化新的 Task<TResult>Initializes a new Task<TResult> with the specified action, state, and options.

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

使用指定的動作、狀態和選項,初始化新的 Task<TResult>Initializes a new Task<TResult> with the specified action, state, and options.

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

使用指定的函式和建立選項,初始化新的 Task<TResult>Initializes a new Task<TResult> with the specified function and creation options.

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

使用指定的動作、狀態和選項,初始化新的 Task<TResult>Initializes a new Task<TResult> with the specified action, state, and options.

Task<TResult>(Func<TResult>)

使用指定的函式,初始化新的 Task<TResult>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))

參數

function
Func<TResult>

委派,表示工作中要執行的程式碼。The delegate that represents the code to execute in the task. 當函式完成時,工作的 Result 屬性會設定成傳回函式的結果值。When the function has completed, the task's Result property will be set to return the result value of the function.

例外狀況

function 引數為 nullThe function argument is null.

function 引數為 nullThe function argument is null.

範例

下列範例會計算代表已發行書籍之文字檔中的大約單字數。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. 呼叫Task.WaitAll(Task[])方法, 以確保所有工作都已完成, 然後才會在主控台中顯示每一本書的字數統計。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. 否則, 它會呼叫Task.Start方法來啟動每個工作。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

正則運算式模式\p{P}*\s+會比對零個、一個或多個標點符號字元, 後面接著一或多個空白字元。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.

備註

此函式只能用於需要建立和啟動工作的「高級」案例中。This constructor should only be used in advanced scenarios where it is required that the creation and starting of the task is separated.

若要將Task<TResult>物件具現化並啟動工作, 最常見的方法就是呼叫靜態Task.Run<TResult>(Func<TResult>)TaskFactory<TResult>.StartNew(Func<TResult>)方法, 而不是呼叫這個函式。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.

如果不需要採取任何動作的工作只是為了讓 API 的取用者有專案等待, TaskCompletionSource<TResult>則應該使用。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.

另請參閱

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

使用指定的函式和狀態,初始化新的 Task<TResult>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);
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)

參數

function
Func<Object,TResult>

委派,表示工作中要執行的程式碼。The delegate that represents the code to execute in the task. 當函式完成時,工作的 Result 屬性會設定成傳回函式的結果值。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.

例外狀況

function 引數為 nullThe function argument is null.

function 引數為 nullThe function argument is null.

備註

若要將Task<TResult>物件具現化並啟動工作, 最常見的方法是呼叫靜態TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object)方法, 而不是呼叫這個函式。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>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>

參數

function
Func<TResult>

委派,表示工作中要執行的程式碼。The delegate that represents the code to execute in the task. 當函式完成時,工作的 Result 屬性會設定成傳回函式的結果值。When the function has completed, the task's Result property will be set to return the result value of the function.

cancellationToken
CancellationToken

要指派給這個工作的 CancellationTokenThe CancellationToken to be assigned to this task.

例外狀況

已處置建立 cancellationTokenCancellationTokenSourceThe CancellationTokenSource that created cancellationToken has already been disposed.

function 引數為 nullThe function argument is null.

function 引數為 nullThe function argument is null.

備註

若要將Task<TResult>物件具現化並啟動工作, 最常見的方法就是呼叫靜態Task.Run<TResult>(Func<TResult>, CancellationToken)TaskFactory<TResult>.StartNew(Func<TResult>, CancellationToken)方法, 而不是呼叫這個函式。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>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)

參數

function
Func<TResult>

委派,表示工作中要執行的程式碼。The delegate that represents the code to execute in the task. 當函式完成時,工作的 Result 屬性會設定成傳回函式的結果值。When the function has completed, the task's Result property will be set to return the result value of the function.

creationOptions
TaskCreationOptions

TaskCreationOptions,用於自訂工作的行為。The TaskCreationOptions used to customize the task's behavior.

例外狀況

creationOptions 引數指定的 TaskCreationOptions 值不正確。The creationOptions argument specifies an invalid value for TaskCreationOptions.

function 引數為 nullThe function argument is null.

function 引數為 nullThe function argument is null.

備註

若要將Task<TResult>物件具現化並啟動工作, 最常見的方法是呼叫靜態TaskFactory<TResult>.StartNew(Func<TResult>, TaskCreationOptions)方法, 而不是呼叫這個函式。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>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);
new System.Threading.Tasks.Task<'Result> : Func<obj, 'Result> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>

參數

function
Func<Object,TResult>

委派,表示工作中要執行的程式碼。The delegate that represents the code to execute in the task. 當函式完成時,工作的 Result 屬性會設定成傳回函式的結果值。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

要指派給新工作的 CancellationTokenThe CancellationToken to be assigned to the new task.

例外狀況

已處置建立 cancellationTokenCancellationTokenSourceThe CancellationTokenSource that created cancellationToken has already been disposed.

function 引數為 nullThe function argument is null.

function 引數為 nullThe function argument is null.

備註

若要將Task<TResult>物件具現化並啟動工作, 最常見的方法是呼叫靜態TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object, CancellationToken)方法, 而不是呼叫這個函式。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>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);
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)

參數

function
Func<Object,TResult>

委派,表示工作中要執行的程式碼。The delegate that represents the code to execute in the task. 當函式完成時,工作的 Result 屬性會設定成傳回函式的結果值。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

TaskCreationOptions,用於自訂工作的行為。The TaskCreationOptions used to customize the task's behavior.

例外狀況

creationOptions 引數指定的 TaskCreationOptions 值不正確。The creationOptions argument specifies an invalid value for TaskCreationOptions.

function 引數為 nullThe function argument is null.

function 引數為 nullThe function argument is null.

備註

若要將Task<TResult>物件具現化並啟動工作, 最常見的方法是呼叫靜態TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object, TaskCreationOptions)方法, 而不是呼叫這個函式。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>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>

參數

function
Func<TResult>

委派,表示工作中要執行的程式碼。The delegate that represents the code to execute in the task. 當函式完成時,工作的 Result 屬性會設定成傳回函式的結果值。When the function has completed, the task's Result property will be set to return the result value of the function.

cancellationToken
CancellationToken

要指派給新工作的 CancellationTokenThe CancellationToken that will be assigned to the new task.

creationOptions
TaskCreationOptions

TaskCreationOptions,用於自訂工作的行為。The TaskCreationOptions used to customize the task's behavior.

例外狀況

已處置建立 cancellationTokenCancellationTokenSourceThe CancellationTokenSource that created cancellationToken has already been disposed.

creationOptions 引數指定的 TaskCreationOptions 值不正確。The creationOptions argument specifies an invalid value for TaskCreationOptions.

function 引數為 nullThe function argument is null.

function 引數為 nullThe function argument is null.

備註

若要將Task<TResult>物件具現化並啟動工作, 最常見的方法是呼叫靜態TaskFactory.StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler)方法, 而不是呼叫這個函式。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>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);
new System.Threading.Tasks.Task<'Result> : Func<obj, 'Result> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>

參數

function
Func<Object,TResult>

委派,表示工作中要執行的程式碼。The delegate that represents the code to execute in the task. 當函式完成時,工作的 Result 屬性會設定成傳回函式的結果值。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

要指派給新工作的 CancellationTokenThe CancellationToken to be assigned to the new task.

creationOptions
TaskCreationOptions

TaskCreationOptions,用於自訂工作的行為。The TaskCreationOptions used to customize the task's behavior.

例外狀況

已處置建立 cancellationTokenCancellationTokenSourceThe CancellationTokenSource that created cancellationToken has already been disposed.

creationOptions 引數指定的 TaskCreationOptions 值不正確。The creationOptions argument specifies an invalid value for TaskCreationOptions.

function 引數為 nullThe function argument is null.

function 引數為 nullThe function argument is null.

備註

若要將Task<TResult>物件具現化並啟動工作, 最常見的方法是呼叫靜態TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)方法, 而不是呼叫這個函式。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.

另請參閱

適用於