Task 建構函式
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
初始化一個新的 Task。
多載
| 名稱 | Description |
|---|---|
| Task(Action) |
初始化一個新的 Task ,並以指定的動作。 |
| Task(Action, CancellationToken) |
初始Task化一個新的,並執行指定的動作。CancellationToken |
| Task(Action, TaskCreationOptions) |
初始化一個新的, Task 並使用指定的動作與創建選項。 |
| Task(Action<Object>, Object) |
初始化一個以指定動作與狀態的新裝置 Task 。 |
| Task(Action, CancellationToken, TaskCreationOptions) |
初始化一個新的, Task 並使用指定的動作與創建選項。 |
| Task(Action<Object>, Object, CancellationToken) |
初始化 Task 一個新的動作,包含指定的動作、狀態和 CancellationToken。 |
| Task(Action<Object>, Object, TaskCreationOptions) |
初始化一個包含指定動作、狀態和選項的新物件 Task 。 |
| Task(Action<Object>, Object, CancellationToken, TaskCreationOptions) |
初始化一個包含指定動作、狀態和選項的新物件 Task 。 |
Task(Action)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
初始化一個新的 Task ,並以指定的動作。
public:
Task(Action ^ action);
public Task(Action action);
new System.Threading.Tasks.Task : Action -> System.Threading.Tasks.Task
Public Sub New (action As Action)
參數
- action
- Action
代表任務中要執行的程式碼的代理。
例外狀況
論 action 點為 null。
範例
以下範例使用 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
open System.Collections.Concurrent
open System.IO
open System.Threading.Tasks
let main =
task {
let list = ConcurrentBag<string>()
let dirNames = [ "."; ".." ]
let tasks = ResizeArray()
for dirName in dirNames do
let t =
new Task(fun () ->
for path in Directory.GetFiles dirName do
list.Add path)
tasks.Add t
t.Start()
do! tasks.ToArray() |> Task.WhenAll
for t in tasks do
printfn $"Task {t.Id} Status: {t.Status}"
printfn $"Number of files read: {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)
Next
End Sub )
tasks.Add(t)
t.Start()
Next
Task.WaitAll(tasks.ToArray())
For Each t In tasks
Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status)
Next
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
open System.Collections.Concurrent
open System.IO
open System.Threading.Tasks
let list = ConcurrentBag<string>()
let dirNames = [ "."; ".." ]
let tasks = ResizeArray()
for dirName in dirNames do
let t =
Task.Run(fun () ->
for path in Directory.GetFiles dirName do
list.Add path)
tasks.Add t
tasks.ToArray() |> Task.WaitAll
for t in tasks do
printfn $"Task {t.Id} Status: {t.Status}"
printfn $"Number of files read: {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)
Next
End Sub )
tasks.Add(t)
Next
Task.WaitAll(tasks.ToArray())
For Each t In tasks
Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status)
Next
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 化物件並啟動任務的方式,是呼叫靜態 Task.Run(Action) 或 TaskFactory.StartNew(Action) 方法。
如果需要一個沒有動作的任務,只是為了讓 API 使用者有東西等待,就應該使用 a TaskCompletionSource<TResult> 。
另請參閱
適用於
Task(Action, CancellationToken)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
初始Task化一個新的,並執行指定的動作。CancellationToken
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)
參數
- action
- Action
代表任務中要執行的程式碼的代理。
- cancellationToken
- CancellationToken
新的 CancellationToken 任務將觀察。
例外狀況
所提供的 CancellationToken 已經被處理掉。
這個 action 論證是空的。
範例
以下範例呼叫 Task(Action, CancellationToken) 建構子來建立一個任務,讓 C:\Windows\System32 目錄中的檔案得以迭代。 lambda 運算 Parallel.ForEach 式呼叫方法,將每個檔案的資訊加入物件 List<T> 。 迴圈呼叫的每個分離巢狀任務 Parallel.ForEach 都會檢查消去標記的狀態,若請求取消,則呼叫該 CancellationToken.ThrowIfCancellationRequested 方法。 當呼叫執行緒呼叫該CancellationToken.ThrowIfCancellationRequested方法時,該OperationCanceledException方法會拋出catch一個例外,該異常會被Task.Wait區塊處理。 接著呼叫該 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
open System
open System.IO
open System.Threading
open System.Threading.Tasks
let main =
task {
use tokenSource = new CancellationTokenSource()
let token = tokenSource.Token
let files = ResizeArray()
let t =
new Task(
(fun () ->
let dir = @"C:\Windows\System32\"
let obj = obj ()
if Directory.Exists dir then
Parallel.ForEach(
Directory.GetFiles dir,
fun f ->
if token.IsCancellationRequested then
token.ThrowIfCancellationRequested()
let fi = FileInfo f
lock obj (fun () -> files.Add(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc))
)
|> ignore),
token
)
t.Start()
tokenSource.Cancel()
try
do! t
printfn $"Retrieved information for {files.Count} files."
with :? AggregateException as e ->
printfn "Exception messages:"
for ie in e.InnerExceptions do
printfn $" {ie.GetType().Name}: {ie.Message}"
printfn $"Task status: {t.Status}"
}
main.Wait()
// 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()
Try
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)
Next
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 化物件並啟動任務的方式,是呼叫靜態 Task.Run(Action, CancellationToken) 與 TaskFactory.StartNew(Action, CancellationToken) 方法。 此建構器唯一的優點是允許物件實例化與任務調用分離。
欲了解更多資訊,請參閱 「任務平行性(任務平行函式庫) 」及 「管理執行緒中的取消」。
適用於
Task(Action, TaskCreationOptions)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
初始化一個新的, 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)
參數
- action
- Action
代表任務中要執行的程式碼的代理。
- creationOptions
- TaskCreationOptions
它們 TaskCreationOptions 用來自訂任務的行為。
例外狀況
這個 action 論證是空的。
該creationOptions參數指定了一個無效的值。TaskCreationOptions
備註
與其呼叫此建構子,最常見的實例 Task 化物件並啟動任務的方式是呼叫靜態 TaskFactory.StartNew(Action, TaskCreationOptions) 方法。 此建構器唯一的優點是允許物件實例化與任務調用分離。
適用於
Task(Action<Object>, Object)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
初始化一個以指定動作與狀態的新裝置 Task 。
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)
參數
- state
- Object
一個代表動作將使用資料的物件。
例外狀況
這個 action 論證是空的。
範例
以下範例定義了一個由六字母組成的詞彙陣列。 每個字作為參數傳遞給 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
open System
open System.Threading.Tasks
let main =
task {
let tasks = ResizeArray()
let rnd = Random()
let lockObj = obj ()
let words6 =
[ "reason"
"editor"
"rioter"
"rental"
"senior"
"regain"
"ordain"
"rained" ]
for word6 in words6 do
let t =
new Task(
(fun word ->
let chars = (string word).ToCharArray()
let order = Array.zeroCreate<double> chars.Length
lock lockObj (fun () ->
for i = 0 to order.Length - 1 do
order[i] <- rnd.NextDouble())
Array.Sort(order, chars)
printfn $"{word} --> {new String(chars)}"),
word6
)
t.Start()
tasks.Add t
do! tasks.ToArray() |> Task.WhenAll
}
main.Wait()
// 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()
Next
End SyncLock
Array.Sort(order, chars)
Console.WriteLine("{0} --> {1}", word,
New String(chars))
End Sub, word6)
t.Start()
tasks.Add(t)
Next
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) 方法。 此建構器唯一的優點是允許物件實例化與任務調用分離。
另請參閱
適用於
Task(Action, CancellationToken, TaskCreationOptions)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
初始化一個新的, Task 並使用指定的動作與創建選項。
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)
參數
- action
- Action
代表任務中要執行的程式碼的代理。
- cancellationToken
- CancellationToken
新的 CancellationToken 任務將觀察。
- creationOptions
- TaskCreationOptions
它們 TaskCreationOptions 用來自訂任務的行為。
例外狀況
CancellationTokenSource那個已經被cancellationToken處理掉的。
這個 action 論證是空的。
該creationOptions參數指定了一個無效的值。TaskCreationOptions
備註
與其呼叫此建構子,最常見的實例 Task 化物件並啟動任務的方式是呼叫靜態 TaskFactory.StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) 方法。 此建構器唯一的優點是允許物件實例化與任務調用分離。
欲了解更多資訊,請參閱 任務平行性(任務平行函式庫) 及 任務取消。
適用於
Task(Action<Object>, Object, CancellationToken)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
初始化 Task 一個新的動作,包含指定的動作、狀態和 CancellationToken。
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)
參數
- state
- Object
一個代表動作將使用資料的物件。
- cancellationToken
- CancellationToken
新的 CancellationToken 任務將觀察。
例外狀況
CancellationTokenSource那個已經被cancellationToken處理掉的。
這個 action 論證是空的。
備註
與其呼叫此建構子,最常見的實例 Task 化物件並啟動任務的方式是呼叫靜態 TaskFactory.StartNew(Action<Object>, Object, CancellationToken) 方法。 此建構器唯一的優點是允許物件實例化與任務調用分離。
適用於
Task(Action<Object>, Object, TaskCreationOptions)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
初始化一個包含指定動作、狀態和選項的新物件 Task 。
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)
參數
- state
- Object
一個代表動作將使用資料的物件。
- creationOptions
- TaskCreationOptions
它們 TaskCreationOptions 用來自訂任務的行為。
例外狀況
這個 action 論證是空的。
該creationOptions參數指定了一個無效的值。TaskCreationOptions
備註
與其呼叫此建構子,最常見的實例 Task 化物件並啟動任務的方式是呼叫靜態 TaskFactory.StartNew(Action<Object>, Object, TaskCreationOptions) 方法。 此建構器唯一的優點是允許物件實例化與任務調用分離。
適用於
Task(Action<Object>, Object, CancellationToken, TaskCreationOptions)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
初始化一個包含指定動作、狀態和選項的新物件 Task 。
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)
參數
- state
- Object
一個代表動作將使用資料的物件。
- cancellationToken
- CancellationToken
新的 CancellationToken 任務將觀察。
- creationOptions
- TaskCreationOptions
它們 TaskCreationOptions 用來自訂任務的行為。
例外狀況
CancellationTokenSource那個已經被cancellationToken處理掉的。
這個 action 論證是空的。
該creationOptions參數指定了一個無效的值。TaskCreationOptions
備註
與其呼叫此建構子,最常見的實例 Task 化物件並啟動任務的方式是呼叫靜態 TaskFactory.StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) 方法。 此建構器唯一的優點是允許物件實例化與任務調用分離。