TaskFactory<TResult> 類別

定義

提供建立和排程 Task<TResult> 物件的支援。Provides support for creating and scheduling Task<TResult> objects.

generic <typename TResult>
public ref class TaskFactory
public class TaskFactory<TResult>
type TaskFactory<'Result> = class
Public Class TaskFactory(Of TResult)

類型參數

TResult

此類別的方法所建立之 Task<TResult> 物件的傳回值。The return value of the Task<TResult> objects that the methods of this class create.

繼承
TaskFactory<TResult>

範例

下列範例會使用靜態Factory屬性,以便在兩個呼叫TaskFactory<TResult>.StartNew方法。The following example uses the static Factory property to make two calls to the TaskFactory<TResult>.StartNew method. 第一項工作會傳回字串陣列,而第二個則會傳回字串陣列,其中會填入使用者的 MyDocuments 目錄之子目錄的名稱填入使用者的 MyDocuments 目錄中的檔案名稱。The first task returns a string array that is populated with the names of files in the user's MyDocuments directory, while the second returns a string array that is populated with the names of subdirectories of the user's MyDocuments directory. 然後它會呼叫TaskFactory.ContinueWhenAll(Task[], Action<Task[]>)方法,這個對話方塊會顯示兩個工作完成執行之後傳回的陣列數目的檔案和目錄的相關資訊。It then calls the TaskFactory.ContinueWhenAll(Task[], Action<Task[]>) method, which displays information about the number of files and directories in the arrays returned by the two tasks after they have completed execution.

using System;
using System.IO;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task<string[]>[] tasks = new Task<string[]>[2];
      String docsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

      tasks[0] = Task<string[]>.Factory.StartNew( () => Directory.GetFiles(docsDirectory));
      tasks[1] = Task<string[]>.Factory.StartNew( () => Directory.GetDirectories(docsDirectory));

      Task.Factory.ContinueWhenAll(tasks, completedTasks => {
                                             Console.WriteLine("{0} contains: ", docsDirectory);
                                             Console.WriteLine("   {0} subdirectories", tasks[1].Result.Length);
                                             Console.WriteLine("   {0} files", tasks[0].Result.Length);
                                          } );
   }
}
// The example displays output like the following:
//       C:\Users\<username>\Documents contains:
//          24 subdirectories
//          16 files
Imports System.IO
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks(1) As Task(Of String())
      Dim docsDirectory As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
      
      tasks(0) = Task(Of String()).Factory.StartNew( Function()Directory.GetFiles(docsDirectory) )
''                                        End Sub )
      tasks(1) = Task(Of String()).Factory.StartNew( Function() Directory.GetDirectories(docsDirectory) )
''                                        End Sub )
      Task.Factory.ContinueWhenAll(tasks, Sub(completedTasks)
                                             Console.WriteLine("{0} contains: ", docsDirectory)
                                             Console.WriteLine("   {0} subdirectories", tasks(1).Result.Length)
                                             Console.WriteLine("   {0} files", tasks(0).Result.Length)
                                          End Sub)
   End Sub
End Module
' The example displays output like the following:
'       C:\Users\<username>\Documents contains:
'          24 subdirectories
'          16 files

備註

.NET Framework 會提供建立和排程工作的兩個處理站:The .NET Framework provides two factories for creating and scheduling tasks:

TaskFactory<TResult>類別可讓您執行下列動作:The TaskFactory<TResult> class allows you to do the following:

  • 建立工作並立即開始藉由呼叫StartNew方法。Create a task and start it immediately by calling the StartNew method. 您可以呼叫此方法來建立和執行的工作需要非預設引數的多載。You can call the overloads of this method to create and execute a task that requires non-default arguments.

    警告

    開頭.NET Framework 4.5.NET Framework 4.5,則Task.Run方法提供最簡單的方式,使用預設組態值建立工作並立即加以啟動。Starting with the .NET Framework 4.5.NET Framework 4.5, the Task.Run method provides the easiest way to create a task with default configuration values and start it immediately.

  • 建立工作,藉由呼叫其中一個陣列中的工作完成時,會啟動ContinueWhenAnyContinueWhenAny方法。Create a task that starts when any one of the tasks in an array has completed by calling the ContinueWhenAny or ContinueWhenAny method.

  • 建立時在陣列中的所有工作都完成藉由呼叫啟動工作ContinueWhenAllContinueWhenAll方法。Create a task that starts when all the tasks in an array have completed by calling the ContinueWhenAll or ContinueWhenAll method.

靜態Task<TResult>.Factory屬性會傳回預設值TaskFactory<TResult>物件。The static Task<TResult>.Factory property returns a default TaskFactory<TResult> object. 您也可以呼叫其中一個TaskFactory<TResult>類別建構函式來設定Task<TResult>物件TaskFactory<TResult>類別會建立。You can also call one of the TaskFactory<TResult> class constructors to configure the Task<TResult> objects that the TaskFactory<TResult> class creates. 下列範例會設定新TaskFactory<TResult>物件來建立具有指定的取消語彙基元、 工作建立選項、 接續選項和自訂的工作排程器工作。The following example configures a new TaskFactory<TResult> object to create tasks that have a specified cancellation token, task creation options, continuation options, and a customized task scheduler.

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

public class Example
{
   static CancellationTokenSource cts = new CancellationTokenSource();

   static TaskFactory<int> factory = new TaskFactory<int>(
      cts.Token,
      TaskCreationOptions.PreferFairness,
      TaskContinuationOptions.ExecuteSynchronously,
      new CustomScheduler());

   static void Main()
   {
      var t2 = factory.StartNew(() => DoWork());
      cts.Dispose();
   }

   static int DoWork()
   {
       /*...*/
       return DateTime.Now.Hour <= 12 ?  1 : 2;
    }
}
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim cts As New CancellationTokenSource()
      Dim factory As New TaskFactory(Of Integer)(
                         cts.Token,
                         TaskCreationOptions.PreferFairness,
                         TaskContinuationOptions.ExecuteSynchronously,
                         New CustomScheduler())

      Dim t2 = factory.StartNew(Function() DoWork())
      cts.Dispose()
   End Sub

   Function DoWork() As Integer
      Return If(Date.Now.Hour <= 12, 1, 2)
   End Function
End Module

在大部分情況下,您就不必具現化新TaskFactory<TResult>執行個體。In most cases, you do not have to instantiate a new TaskFactory<TResult> instance. 相反地,您可以使用靜態Task<TResult>.Factory屬性,會傳回 factory 物件,會使用預設值。Instead, you can use the static Task<TResult>.Factory property, which returns a factory object that uses default values. 然後,您可以呼叫其方法來啟動新的工作,或定義工作接續。You can then call its methods to start new tasks or define task continuations. 如需圖例,請參閱範例。For an illustration, see the example.

建構函式

TaskFactory<TResult>()

使用預設組態,初始化 TaskFactory<TResult> 執行個體。Initializes a TaskFactory<TResult> instance with the default configuration.

TaskFactory<TResult>(CancellationToken)

使用預設組態,初始化 TaskFactory<TResult> 執行個體。Initializes a TaskFactory<TResult> instance with the default configuration.

TaskFactory<TResult>(CancellationToken, TaskCreationOptions, TaskContinuationOptions, TaskScheduler)

使用指定的組態,初始化 TaskFactory<TResult> 執行個體。Initializes a TaskFactory<TResult> instance with the specified configuration.

TaskFactory<TResult>(TaskCreationOptions, TaskContinuationOptions)

使用指定的組態,初始化 TaskFactory<TResult> 執行個體。Initializes a TaskFactory<TResult> instance with the specified configuration.

TaskFactory<TResult>(TaskScheduler)

使用指定的組態,初始化 TaskFactory<TResult> 執行個體。Initializes a TaskFactory<TResult> instance with the specified configuration.

屬性

CancellationToken

取得這個工作 Factory 的預設取消語彙基元。Gets the default cancellation token for this task factory.

ContinuationOptions

取得這個工作 Factory 的 TaskContinuationOptions 列舉值。Gets the TaskContinuationOptions enumeration value for this task factory.

CreationOptions

取得這個工作 Factory 的 TaskCreationOptions 列舉值。Gets the TaskCreationOptions enumeration value for this task factory.

Scheduler

取得這個工作 Factory 的工作排程器。Gets the task scheduler for this task factory.

方法

ContinueWhenAll(Task[], Func<Task[],TResult>)

建立會在提供的一組工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of a set of provided tasks.

ContinueWhenAll(Task[], Func<Task[],TResult>, CancellationToken)

建立會在提供的一組工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of a set of provided tasks.

ContinueWhenAll(Task[], Func<Task[],TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)

建立會在提供的一組工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of a set of provided Tasks.

ContinueWhenAll(Task[], Func<Task[],TResult>, TaskContinuationOptions)

建立會在提供的一組工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of a set of provided Tasks.

ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>[],TResult>)

建立會在提供的一組工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of a set of provided tasks.

ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>[],TResult>, CancellationToken)

建立會在提供的一組工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of a set of provided tasks.

ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>[],TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)

建立會在提供的一組工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of a set of provided tasks.

ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>[],TResult>, TaskContinuationOptions)

建立會在提供的一組工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of a set of provided tasks.

ContinueWhenAny(Task[], Func<Task,TResult>)

建立會在提供的任何一項工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of any task in the provided set.

ContinueWhenAny(Task[], Func<Task,TResult>, CancellationToken)

建立會在提供的任何一項工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of any task in the provided set.

ContinueWhenAny(Task[], Func<Task,TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)

建立會在提供的任何一項工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of any task in the provided set.

ContinueWhenAny(Task[], Func<Task,TResult>, TaskContinuationOptions)

建立會在提供的任何一項工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of any task in the provided set.

ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>,TResult>)

建立會在提供的任何一項工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of any task in the provided set.

ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>,TResult>, CancellationToken)

建立會在提供的任何一項工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of any task in the provided set.

ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>,TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)

建立會在提供的任何一項工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of any task in the provided set.

ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[], Func<Task<TAntecedentResult>,TResult>, TaskContinuationOptions)

建立會在提供的任何一項工作完成時啟動的接續工作。Creates a continuation task that will be started upon the completion of any task in the provided set.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Func<IAsyncResult,TResult>, Object)

建立工作,這個項目表示一組符合「非同步程式設計模型」模式的開始和結束方法。Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern.

FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Func<IAsyncResult,TResult>, Object, TaskCreationOptions)

建立工作,這個項目表示一組符合「非同步程式設計模型」模式的開始和結束方法。Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern.

FromAsync(IAsyncResult, Func<IAsyncResult,TResult>)

建立工作,當指定的 IAsyncResult 完成時會執行結束方法函式。Creates a task that executes an end method function when a specified IAsyncResult completes.

FromAsync(IAsyncResult, Func<IAsyncResult,TResult>, TaskCreationOptions)

建立工作,當指定的 IAsyncResult 完成時會執行結束方法函式。Creates a task that executes an end method function when a specified IAsyncResult completes.

FromAsync(IAsyncResult, Func<IAsyncResult,TResult>, TaskCreationOptions, TaskScheduler)

建立工作,當指定的 IAsyncResult 完成時會執行結束方法函式。Creates a task that executes an end method function when a specified IAsyncResult completes.

FromAsync<TArg1,TArg2,TArg3>(Func<TArg1,TArg2,TArg3,AsyncCallback,Object,IAsyncResult>, Func<IAsyncResult,TResult>, TArg1, TArg2, TArg3, Object)

建立工作,這個項目表示一組符合「非同步程式設計模型」模式的開始和結束方法。Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern.

FromAsync<TArg1,TArg2,TArg3>(Func<TArg1,TArg2,TArg3,AsyncCallback,Object,IAsyncResult>, Func<IAsyncResult,TResult>, TArg1, TArg2, TArg3, Object, TaskCreationOptions)

建立工作,這個項目表示一組符合「非同步程式設計模型」模式的開始和結束方法。Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern.

FromAsync<TArg1,TArg2>(Func<TArg1,TArg2,AsyncCallback,Object,IAsyncResult>, Func<IAsyncResult,TResult>, TArg1, TArg2, Object)

建立工作,這個項目表示一組符合「非同步程式設計模型」模式的開始和結束方法。Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern.

FromAsync<TArg1,TArg2>(Func<TArg1,TArg2,AsyncCallback,Object,IAsyncResult>, Func<IAsyncResult,TResult>, TArg1, TArg2, Object, TaskCreationOptions)

建立工作,這個項目表示一組符合「非同步程式設計模型」模式的開始和結束方法。Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern.

FromAsync<TArg1>(Func<TArg1,AsyncCallback,Object,IAsyncResult>, Func<IAsyncResult,TResult>, TArg1, Object)

建立工作,這個項目表示一組符合「非同步程式設計模型」模式的開始和結束方法。Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern.

FromAsync<TArg1>(Func<TArg1,AsyncCallback,Object,IAsyncResult>, Func<IAsyncResult,TResult>, TArg1, Object, TaskCreationOptions)

建立工作,這個項目表示一組符合「非同步程式設計模型」模式的開始和結束方法。Creates a task that represents a pair of begin and end methods that conform to the Asynchronous Programming Model pattern.

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
StartNew(Func<Object,TResult>, Object)

建立並啟動工作。Creates and starts a task.

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

建立並啟動工作。Creates and starts a task.

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

建立並啟動工作。Creates and starts a task.

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

建立並啟動工作。Creates and starts a task.

StartNew(Func<TResult>)

建立並啟動工作。Creates and starts a task.

StartNew(Func<TResult>, CancellationToken)

建立並啟動工作。Creates and starts a task.

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

建立並啟動工作。Creates and starts a task.

StartNew(Func<TResult>, TaskCreationOptions)

建立並啟動工作。Creates and starts a task.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

適用於

執行緒安全性

所有 public 和 protected 成員TaskFactory<TResult>是安全執行緒,且可能會從多個執行緒同時使用。All public and protected members of TaskFactory<TResult> are thread-safe and may be used concurrently from multiple threads.

另請參閱