Task(Action ^ action);
public Task (Action action);
new System.Threading.Tasks.Task : Action -> System.Threading.Tasks.Task
Public Sub New (action As Action)

下列範例會使用 建 Task(Action) 構函式來建立工作,以擷取指定目錄中的檔案名。 所有工作都會將檔案名寫入至單 ConcurrentBag<T> 一物件。 此範例接著會呼叫 WaitAll(Task[]) 方法,以確保所有工作都已完成,然後顯示寫入 ConcurrentBag<T> 物件之檔案名總數的計數。

using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class Example public static async Task Main() var list = new ConcurrentBag<string>(); string[] dirNames = { ".", ".." }; List<Task> tasks = new List<Task>(); foreach (var dirName in dirNames) { Task t = new Task( () => { foreach(var path in Directory.GetFiles(dirName)) list.Add(path); } ); tasks.Add(t); t.Start(); await Task.WhenAll(tasks.ToArray()); foreach (Task t in tasks) Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status); Console.WriteLine("Number of files read: {0}", list.Count); // The example displays output like the following: // Task 1 Status: RanToCompletion // Task 2 Status: RanToCompletion // Number of files read: 23 Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.IO Imports System.Threading.Tasks Module Example Public Sub Main() Dim list As New ConcurrentBag(Of String)() Dim dirNames() As String = { ".", ".." } Dim tasks As New List(Of Task)() For Each dirName In dirNames Dim t As New Task( Sub() For Each path In Directory.GetFiles(dirName) list.Add(path) End Sub ) tasks.Add(t) t.Start() Task.WaitAll(tasks.ToArray()) For Each t In tasks Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status) Console.WriteLine("Number of files read: {0}", list.Count) End Sub End Module ' The example displays output like the following: ' Task 1 Status: RanToCompletion ' Task 2 Status: RanToCompletion ' Number of files read: 23

下列範例完全相同,不同之處在于它會使用 Run(Action) 方法在單一作業中具現化並執行工作。 方法會傳 Task 回代表工作的 物件。

using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class Example public static void Main() var list = new ConcurrentBag<string>(); string[] dirNames = { ".", ".." }; List<Task> tasks = new List<Task>(); foreach (var dirName in dirNames) { Task t = Task.Run( () => { foreach(var path in Directory.GetFiles(dirName)) list.Add(path); } ); tasks.Add(t); Task.WaitAll(tasks.ToArray()); foreach (Task t in tasks) Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status); Console.WriteLine("Number of files read: {0}", list.Count); // The example displays output like the following: // Task 1 Status: RanToCompletion // Task 2 Status: RanToCompletion // Number of files read: 23 Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.IO Imports System.Threading.Tasks Module Example Public Sub Main() Dim list As New ConcurrentBag(Of String)() Dim dirNames() As String = { ".", ".." } Dim tasks As New List(Of Task)() For Each dirName In dirNames Dim t As Task = Task.Run( Sub() For Each path In Directory.GetFiles(dirName) list.Add(path) End Sub ) tasks.Add(t) Task.WaitAll(tasks.ToArray()) For Each t In tasks Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status) Console.WriteLine("Number of files read: {0}", list.Count) End Sub End Module ' The example displays output like the following: ' Task 1 Status: RanToCompletion ' Task 2 Status: RanToCompletion ' Number of files read: 23

此建構函式應該只用于需要建立和啟動工作的進階案例中。

呼叫靜態 Task.Run(Action) TaskFactory.StartNew(Action) 方法,而不是呼叫這個建構函式,這是具現化 Task 物件並啟動工作最常見的方式。

如果只需要 API 的取用者要等候某個專案,就不需要採取任何動作的工作, TaskCompletionSource<TResult> 就應該使用 。

public:
 Task(Action ^ action, System::Threading::CancellationToken cancellationToken);
public Task (Action action, System.Threading.CancellationToken cancellationToken);
new System.Threading.Tasks.Task : Action * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Sub New (action As Action, cancellationToken As CancellationToken)

下列範例會呼叫 建 Task(Action, CancellationToken) 構函式來建立工作,以逐一查看 C:\Windows\System32 目錄中的檔案。 Lambda 運算式會呼叫 方法, Parallel.ForEach 將每個檔案的相關資訊新增至 List<T> 物件。 迴圈叫 Parallel.ForEach 用的每個中斷連結巢狀工作都會檢查解除標記的狀態,如果要求取消,則會呼叫 CancellationToken.ThrowIfCancellationRequested 方法。 方法 CancellationToken.ThrowIfCancellationRequested 會在 OperationCanceledException 呼叫執行緒呼叫 Task.Wait 方法時擲回區塊中 catch 處理的例外狀況。 接著會 Start 呼叫 方法來啟動工作。

using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; public class Example public static async Task Main() var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; var files = new List<Tuple<string, string, long, DateTime>>(); var t = new Task(() => { 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); t.Start(); tokenSource.Cancel(); try { await t; 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 Imports System.Collections.Generic Imports System.IO Imports System.Threading Imports System.Threading.Tasks Module Example Public Sub Main() Dim tokenSource As New CancellationTokenSource() Dim token As CancellationToken = tokenSource.Token Dim files As New List(Of Tuple(Of String, String, Long, Date))() Dim t As New Task(Sub() Dim dir As String = "C:\Windows\System32\" Dim obj As New Object() If Directory.Exists(dir)Then Parallel.ForEach(Directory.GetFiles(dir), Sub(f) If token.IsCancellationRequested Then token.ThrowIfCancellationRequested() End If Dim fi As New FileInfo(f) SyncLock(obj) files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc)) End SyncLock End Sub) End If End Sub, token) t.Start() tokenSource.Cancel() t.Wait() Console.WriteLine("Retrieved information for {0} files.", files.Count) Catch e As AggregateException Console.WriteLine("Exception messages:") For Each ie As Exception In e.InnerExceptions Console.WriteLine(" {0}:{1}", ie.GetType().Name, ie.Message) Console.WriteLine() Console.WriteLine("Task status: {0}", t.Status) Finally tokenSource.Dispose() End Try End Sub End Module ' The example displays the following output: ' Exception messages: ' TaskCanceledException: A task was canceled. ' Task status: Canceled

呼叫靜態 Task.Run(Action, CancellationToken) TaskFactory.StartNew(Action, CancellationToken) 方法,而不是呼叫這個建構函式,將物件具現化 Task 並啟動工作最常見的方式。 這個建構函式所提供的唯一優點是它允許物件具現化與工作調用分開。

如需詳細資訊,請參閱工作 平行處理原則 ( 受控執行緒中 的工作平行程式庫) 和取消。

public:
 Task(Action ^ action, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Action action, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task : Action * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Sub New (action As Action, creationOptions As TaskCreationOptions)
public:
 Task(Action<System::Object ^> ^ action, System::Object ^ state);
public Task (Action<object> action, object state);
public Task (Action<object?> action, object? state);
new System.Threading.Tasks.Task : Action<obj> * obj -> System.Threading.Tasks.Task
Public Sub New (action As Action(Of Object), state As Object)

下列範例會定義 6 個字母字組的陣列。 然後,每個字都會當做引數傳遞至 Task(Action<Object>, Object) 建構函式,其 Action<T> 委派會拼字中的字元,然後顯示原始字組及其拼字版本。

using System; using System.Collections.Generic; using System.Threading.Tasks; public class Example public static async Task 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) { Task t = new Task( (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); t.Start(); tasks.Add(t); await Task.WhenAll(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 Imports System.Collections.Generic Imports System.Threading.Tasks Module Example Public Sub Main() Dim tasks As New List(Of Task)() Dim rnd As New Random() Dim lockObj As New Object() Dim words6() As String = { "reason", "editor", "rioter", "rental", "senior", "regain", "ordain", "rained" } For Each word6 in words6 Dim t As New Task( Sub(word) Dim chars() As Char = word.ToString().ToCharArray() Dim order(chars.Length - 1) As Double SyncLock lockObj For ctr As Integer = 0 To order.Length - 1 order(ctr) = rnd.NextDouble() End SyncLock Array.Sort(order, chars) Console.WriteLine("{0} --> {1}", word, New String(chars)) End Sub, word6) t.Start() tasks.Add(t) Task.WaitAll(tasks.ToArray()) End Sub End Module ' The example displays output like the following: ' regain --> irnaeg ' ordain --> rioadn ' reason --> soearn ' rained --> rinade ' rioter --> itrore ' senior --> norise ' rental --> atnerl ' editor --> oteird

若要具現化 Task 物件並啟動工作,而不是呼叫這個建構函式,最常見的方式是呼叫靜態 TaskFactory.StartNew(Action<Object>, Object) 方法。 這個建構函式所提供的唯一優點是它允許物件具現化與工作調用分開。

public:
 Task(Action ^ action, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Action action, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task : Action * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Sub New (action As Action, cancellationToken As CancellationToken, creationOptions As TaskCreationOptions)

若要具現化 Task 物件並啟動工作,而不是呼叫這個建構函式,最常見的方式是呼叫靜態 TaskFactory.StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) 方法。 這個建構函式所提供的唯一優點是它允許物件具現化與工作調用分開。

如需詳細資訊,請參閱 工作平行處理原則 (工作平行程式庫) 工作取消

public:
 Task(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::CancellationToken cancellationToken);
public Task (Action<object> action, object state, System.Threading.CancellationToken cancellationToken);
public Task (Action<object?> action, object? state, System.Threading.CancellationToken cancellationToken);
new System.Threading.Tasks.Task : Action<obj> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Sub New (action As Action(Of Object), state As Object, cancellationToken As CancellationToken)
public:
 Task(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Action<object> action, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
public Task (Action<object?> action, object? state, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task : Action<obj> * obj * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Sub New (action As Action(Of Object), state As Object, creationOptions As TaskCreationOptions)
public:
 Task(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Action<object> action, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
public Task (Action<object?> action, object? state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task : Action<obj> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Sub New (action As Action(Of Object), state As Object, cancellationToken As CancellationToken, creationOptions As TaskCreationOptions)