Task.Run 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将在线程池上运行的指定工作排队,并返回该工作的任务或 Task<TResult> 句柄。
重载
Run(Func<Task>, CancellationToken) |
将在线程池上运行的指定工作排队,并返回 |
Run(Action, CancellationToken) |
将在线程池上运行的指定工作排队,并返回代表该工作的 Task 对象。 可使用取消标记来取消工作(如果尚未启动)。 |
Run(Func<Task>) |
将在线程池上运行的指定工作排队,并返回 |
Run(Action) |
将在线程池上运行的指定工作排队,并返回代表该工作的 Task 对象。 |
Run<TResult>(Func<Task<TResult>>) |
将指定的工作排成队列在线程池上运行,并返回由 |
Run<TResult>(Func<TResult>) |
将在线程池上运行的指定工作排队,并返回代表该工作的 Task<TResult> 对象。 可使用取消标记来取消工作(如果尚未启动)。 |
Run<TResult>(Func<Task<TResult>>, CancellationToken) |
将指定的工作排成队列在线程池上运行,并返回由 |
Run<TResult>(Func<TResult>, CancellationToken) |
将在线程池上运行的指定工作排队,并返回代表该工作的 |
注解
方法 Run 提供一组重载,以便使用默认值轻松启动任务。 它是重载的 StartNew 轻型替代项。
Run(Func<Task>, CancellationToken)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
将在线程池上运行的指定工作排队,并返回 function
所返回的任务的代理项。 可使用取消标记来取消工作(如果尚未启动)。
public:
static System::Threading::Tasks::Task ^ Run(Func<System::Threading::Tasks::Task ^> ^ function, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task Run (Func<System.Threading.Tasks.Task> function, System.Threading.CancellationToken cancellationToken);
public static System.Threading.Tasks.Task Run (Func<System.Threading.Tasks.Task?> function, System.Threading.CancellationToken cancellationToken);
static member Run : Func<System.Threading.Tasks.Task> * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Shared Function Run (function As Func(Of Task), cancellationToken As CancellationToken) As Task
参数
- cancellationToken
- CancellationToken
可用于取消工作(如果尚未启动)的取消标记。 Run(Func<Task>, CancellationToken) 不会将 cancellationToken
传递到 action
。
返回
表示由 function
返回的任务代理的任务。
例外
function
参数是 null
。
该任务已取消。 此异常存储在返回的任务中。
与 cancellationToken
关联的 CancellationTokenSource 已释放。
注解
有关处理任务操作引发的异常的信息,请参阅 异常处理。
另请参阅
适用于
Run(Action, CancellationToken)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
将在线程池上运行的指定工作排队,并返回代表该工作的 Task 对象。 可使用取消标记来取消工作(如果尚未启动)。
public:
static System::Threading::Tasks::Task ^ Run(Action ^ action, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task Run (Action action, System.Threading.CancellationToken cancellationToken);
static member Run : Action * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Shared Function Run (action As Action, cancellationToken As CancellationToken) As Task
参数
- action
- Action
以异步方式执行的工作。
- cancellationToken
- CancellationToken
可用于取消工作(如果尚未启动)的取消标记。 Run(Action, CancellationToken) 不会将 cancellationToken
传递到 action
。
返回
一个任务,它表示在线程池中排队等待执行的工作。
例外
action
参数是 null
。
该任务已取消。 此异常存储在返回的任务中。
与 cancellationToken
关联的 CancellationTokenSource 已释放。
示例
以下示例调用 Run(Action, CancellationToken) 方法以创建循环访问 C:\Windows\System32 目录中的文件的任务。 lambda 表达式调用 方法, Parallel.ForEach 以将有关每个文件的信息添加到 List<T> 对象。 循环 Parallel.ForEach 调用的每个分离嵌套任务都会检查取消令牌的状态,如果请求取消,则 CancellationToken.ThrowIfCancellationRequested 调用 方法。 当调用线程调用 Task.Wait 方法时, CancellationToken.ThrowIfCancellationRequested 方法将引发OperationCanceledException在 块中catch
处理的异常。
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 = Task.Run( () => { 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);
await Task.Yield();
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.
// 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 =
Task.Run(
(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
)
do! Task.Yield()
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.
// 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 Task = Task.Run( 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)
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
注解
如果在任务开始执行之前请求取消,则不会执行该任务。 而是将其设置为 Canceled 状态并引发 TaskCanceledException 异常。
方法 Run(Action, CancellationToken) 是 方法的更简单替代 TaskFactory.StartNew(Action, CancellationToken) 方法。 它创建具有以下默认值的任务:
它使用默认的任务计划程序。
有关处理任务操作引发的异常的信息,请参阅 异常处理。
另请参阅
适用于
Run(Func<Task>)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
将在线程池上运行的指定工作排队,并返回 function
所返回的任务的代理项。
public:
static System::Threading::Tasks::Task ^ Run(Func<System::Threading::Tasks::Task ^> ^ function);
public static System.Threading.Tasks.Task Run (Func<System.Threading.Tasks.Task> function);
public static System.Threading.Tasks.Task Run (Func<System.Threading.Tasks.Task?> function);
static member Run : Func<System.Threading.Tasks.Task> -> System.Threading.Tasks.Task
Public Shared Function Run (function As Func(Of Task)) As Task
参数
返回
表示由 function
返回的任务代理的任务。
例外
function
参数是 null
。
注解
有关处理任务操作引发的异常的信息,请参阅 异常处理。
另请参阅
适用于
Run(Action)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
将在线程池上运行的指定工作排队,并返回代表该工作的 Task 对象。
public:
static System::Threading::Tasks::Task ^ Run(Action ^ action);
public static System.Threading.Tasks.Task Run (Action action);
static member Run : Action -> System.Threading.Tasks.Task
Public Shared Function Run (action As Action) As Task
参数
- action
- Action
以异步方式执行的工作。
返回
表示在线程池执行的队列的任务。
例外
action
参数是 null
。
示例
以下示例定义一个 ShowThreadInfo
显示 Thread.ManagedThreadId 当前线程的 的方法。 它直接从应用程序线程调用,并从传递给 方法的 Action 委托中 Run(Action) 调用。
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
ShowThreadInfo("Application");
var t = Task.Run(() => ShowThreadInfo("Task") );
t.Wait();
}
static void ShowThreadInfo(String s)
{
Console.WriteLine("{0} thread ID: {1}",
s, Thread.CurrentThread.ManagedThreadId);
}
}
// The example displays the following output:
// Application thread ID: 1
// Task thread ID: 3
open System.Threading
open System.Threading.Tasks
let showThreadInfo s =
printfn $"%s{s} thread ID: {Thread.CurrentThread.ManagedThreadId}"
showThreadInfo "Application"
let t = Task.Run(fun () -> showThreadInfo "Task")
t.Wait()
// The example displays the following output:
// Application thread ID: 1
// Task thread ID: 3
Imports System.Threading
Imports System.Threading.Tasks
Module Example
Public Sub Main()
ShowThreadInfo("Application")
Dim t As Task = Task.Run(Sub() ShowThreadInfo("Task") )
t.Wait()
End Sub
Private Sub ShowThreadInfo(s As String)
Console.WriteLine("{0} Thread ID: {1}",
s, Thread.CurrentThread.ManagedThreadId)
End Sub
End Module
' The example displays output like the following:
' Application thread ID: 1
' Task thread ID: 3
下面的示例与上一个示例类似,只不过它使用 lambda 表达式来定义任务要执行的代码。
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
Console.WriteLine("Application thread ID: {0}",
Thread.CurrentThread.ManagedThreadId);
var t = Task.Run(() => { Console.WriteLine("Task thread ID: {0}",
Thread.CurrentThread.ManagedThreadId);
} );
t.Wait();
}
}
// The example displays the following output:
// Application thread ID: 1
// Task thread ID: 3
open System.Threading
open System.Threading.Tasks
printfn $"Application thread ID: {Thread.CurrentThread.ManagedThreadId}"
let t = Task.Run(fun () -> printfn $"Task thread ID: {Thread.CurrentThread.ManagedThreadId}")
t.Wait()
// The example displays the following output:
// Application thread ID: 1
// Task thread ID: 3
Imports System.Threading
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Console.WriteLine("Application thread ID: {0}",
Thread.CurrentThread.ManagedThreadId)
Dim t As Task = Task.Run(Sub()
Console.WriteLine("Task thread ID: {0}",
Thread.CurrentThread.ManagedThreadId)
End Sub)
t.Wait()
End Sub
End Module
' The example displays output like the following:
' Application thread ID: 1
' Task thread ID: 3
这些示例显示异步任务在与main应用程序线程不同的线程上执行。
Wait调用 方法可确保任务在应用程序结束之前完成并显示其输出。 否则,方法可能在 Main
任务完成之前完成。
下面的示例演示 Run(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 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
注解
方法 Run 允许在单个方法调用中创建和执行任务,并且是 方法的更简单替代方法 StartNew 。 它创建具有以下默认值的任务:
其取消标记为 CancellationToken.None。
它使用默认的任务计划程序。
有关处理任务操作引发的异常的信息,请参阅 异常处理。
另请参阅
适用于
Run<TResult>(Func<Task<TResult>>)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
将指定的工作排成队列在线程池上运行,并返回由 function
返回的 Task(TResult)
的代理。 可使用取消标记来取消工作(如果尚未启动)。
public:
generic <typename TResult>
static System::Threading::Tasks::Task<TResult> ^ Run(Func<System::Threading::Tasks::Task<TResult> ^> ^ function);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<System.Threading.Tasks.Task<TResult>> function);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<System.Threading.Tasks.Task<TResult>?> function);
static member Run : Func<System.Threading.Tasks.Task<'Result>> -> System.Threading.Tasks.Task<'Result>
Public Shared Function Run(Of TResult) (function As Func(Of Task(Of TResult))) As Task(Of TResult)
类型参数
- TResult
代理任务返回的结果的类型。
参数
返回
表示由 Task(TResult)
返回的 Task(TResult)
的代理的 function
。
例外
function
参数是 null
。
注解
有关处理任务操作引发的异常的信息,请参阅 异常处理。
另请参阅
适用于
Run<TResult>(Func<TResult>)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
将在线程池上运行的指定工作排队,并返回代表该工作的 Task<TResult> 对象。 可使用取消标记来取消工作(如果尚未启动)。
public:
generic <typename TResult>
static System::Threading::Tasks::Task<TResult> ^ Run(Func<TResult> ^ function);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<TResult> function);
static member Run : Func<'Result> -> System.Threading.Tasks.Task<'Result>
Public Shared Function Run(Of TResult) (function As Func(Of TResult)) As Task(Of TResult)
类型参数
- TResult
任务的返回类型。
参数
- function
- Func<TResult>
以异步方式执行的工作。
返回
表示在线程池中排队执行的工作的任务对象。
例外
function
参数为 null
。
示例
以下示例计算文本文件中表示已出版书籍的大致字数。 每个任务负责打开文件、异步读取其整个内容以及使用正则表达式计算字数计数。 WaitAll(Task[])调用 方法以确保在向控制台显示每本书的字数之前已完成所有任务。
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public class Example
{
public static void 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] = Task.Run( () => {
// Number of words.
int nWords = 0;
// Create filename from title.
string fn = s + ".txt";
if (File.Exists(fn)) {
StreamReader sr = new StreamReader(fn);
string input = sr.ReadToEndAsync().Result;
nWords = Regex.Matches(input, pattern).Count;
}
return nWords;
} );
}
Task.WaitAll(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
open System
open System.IO
open System.Text.RegularExpressions
open System.Threading.Tasks
let pattern = @"\p{P}*\s+"
let titles = [| "Sister Carrie"; "The Financier" |]
let tasks =
Array.map (fun title ->
Task.Run(fun () ->
// Create filename from title.
let fn = title + ".txt"
if File.Exists fn then
use sr = new StreamReader(fn)
let input = sr.ReadToEndAsync().Result
Regex.Matches(input, pattern).Count
else
0)) titles
tasks |> Seq.cast |> Array.ofSeq |> Task.WaitAll
printfn "Word Counts:\n"
for i = 0 to tasks.Length - 1 do
printfn $"%s{titles.[i]}: %10d{tasks.[i].Result} words"
// 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) = Task.Run( Function()
' Number of words.
Dim nWords As Integer = 0
' Create filename from title.
Dim fn As String = s + ".txt"
If File.Exists(fn) Then
Dim sr As New StreamReader(fn)
Dim input As String = sr.ReadToEndAsync().Result
nWords = Regex.Matches(input, pattern).Count
End If
Return nWords
End Function)
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 Sub
End Module
' The example displays the following output:
' Sister Carrie: 159,374 words
' The Financier: 196,362 words
正则表达式 \p{P}*\s+
匹配零个、一个或多个标点字符,后跟一个或多个空格字符。 它假定匹配项总数等于近似字数计数。
注解
方法 Run 是 方法的更简单替代 TaskFactory.StartNew(Action) 方法。 它创建具有以下默认值的任务:
其取消标记为 CancellationToken.None。
它使用默认的任务计划程序。
有关处理任务操作引发的异常的信息,请参阅 异常处理。
另请参阅
适用于
Run<TResult>(Func<Task<TResult>>, CancellationToken)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
将指定的工作排成队列在线程池上运行,并返回由 function
返回的 Task(TResult)
的代理。
public:
generic <typename TResult>
static System::Threading::Tasks::Task<TResult> ^ Run(Func<System::Threading::Tasks::Task<TResult> ^> ^ function, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<System.Threading.Tasks.Task<TResult>> function, System.Threading.CancellationToken cancellationToken);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<System.Threading.Tasks.Task<TResult>?> function, System.Threading.CancellationToken cancellationToken);
static member Run : Func<System.Threading.Tasks.Task<'Result>> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>
Public Shared Function Run(Of TResult) (function As Func(Of Task(Of TResult)), cancellationToken As CancellationToken) As Task(Of TResult)
类型参数
- TResult
代理任务返回的结果的类型。
参数
- cancellationToken
- CancellationToken
可用于取消工作(如果尚未启动)的取消标记。 Run<TResult>(Func<Task<TResult>>, CancellationToken) 不会将 cancellationToken
传递到 action
。
返回
表示由 Task(TResult)
返回的 Task(TResult)
的代理的 function
。
例外
function
参数是 null
。
该任务已取消。 此异常存储在返回的任务中。
与 cancellationToken
关联的 CancellationTokenSource 已释放。
注解
有关处理任务操作引发的异常的信息,请参阅 异常处理。
另请参阅
适用于
Run<TResult>(Func<TResult>, CancellationToken)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
将在线程池上运行的指定工作排队,并返回代表该工作的 Task(TResult)
对象。
public:
generic <typename TResult>
static System::Threading::Tasks::Task<TResult> ^ Run(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<TResult> function, System.Threading.CancellationToken cancellationToken);
static member Run : Func<'Result> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>
Public Shared Function Run(Of TResult) (function As Func(Of TResult), cancellationToken As CancellationToken) As Task(Of TResult)
类型参数
- TResult
任务的结果类型。
参数
- function
- Func<TResult>
以异步方式执行的工作。
- cancellationToken
- CancellationToken
可用于取消工作(如果尚未启动)的取消标记。 Run<TResult>(Func<TResult>, CancellationToken) 不会将 cancellationToken
传递到 action
。
返回
一个 Task(TResult)
,它表示在线程池中排队等待执行的工作。
例外
function
参数为 null
。
该任务已取消。 此异常存储在返回的任务中。
与 cancellationToken
关联的 CancellationTokenSource 已释放。
示例
以下示例创建 20 个任务,这些任务将循环执行,直到计数器递增为值 200 万。 当前 10 个任务达到 200 万时,取消令牌将被取消,并且计数器未达到 200 万的任何任务将被取消。 该示例显示了可能的输出。
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
var tasks = new List<Task<int>>();
var source = new CancellationTokenSource();
var token = source.Token;
int completedIterations = 0;
for (int n = 0; n <= 19; n++)
tasks.Add(Task.Run( () => { int iterations = 0;
for (int ctr = 1; ctr <= 2000000; ctr++) {
token.ThrowIfCancellationRequested();
iterations++;
}
Interlocked.Increment(ref completedIterations);
if (completedIterations >= 10)
source.Cancel();
return iterations; }, token));
Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
try {
Task.WaitAll(tasks.ToArray());
}
catch (AggregateException) {
Console.WriteLine("Status of tasks:\n");
Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
"Status", "Iterations");
foreach (var t in tasks)
Console.WriteLine("{0,10} {1,20} {2,14}",
t.Id, t.Status,
t.Status != TaskStatus.Canceled ? t.Result.ToString("N0") : "n/a");
}
}
}
// The example displays output like the following:
// Waiting for the first 10 tasks to complete...
// Status of tasks:
//
// Task Id Status Iterations
// 1 RanToCompletion 2,000,000
// 2 RanToCompletion 2,000,000
// 3 RanToCompletion 2,000,000
// 4 RanToCompletion 2,000,000
// 5 RanToCompletion 2,000,000
// 6 RanToCompletion 2,000,000
// 7 RanToCompletion 2,000,000
// 8 RanToCompletion 2,000,000
// 9 RanToCompletion 2,000,000
// 10 Canceled n/a
// 11 Canceled n/a
// 12 Canceled n/a
// 13 Canceled n/a
// 14 Canceled n/a
// 15 Canceled n/a
// 16 RanToCompletion 2,000,000
// 17 Canceled n/a
// 18 Canceled n/a
// 19 Canceled n/a
// 20 Canceled n/a
open System
open System.Collections.Generic
open System.Threading
open System.Threading.Tasks
let source = new CancellationTokenSource()
let token = source.Token
let mutable completedIterations = 0
let tasks =
[| for _ = 0 to 19 do
Task.Run(
(fun () ->
let mutable iterations = 0
for _ = 1 to 2000000 do
token.ThrowIfCancellationRequested()
iterations <- iterations + 1
Interlocked.Increment &completedIterations |> ignore
if completedIterations >= 10 then
source.Cancel()
iterations),
token
)
|]
printfn "Waiting for the first 10 tasks to complete...\n"
try
tasks |> Seq.cast |> Array.ofSeq |> Task.WaitAll
with :? AggregateException ->
printfn "Status of tasks:\n"
printfn "%10s %20s %14s" "Task Id" "Status" "Iterations"
for t in tasks do
if t.Status <> TaskStatus.Canceled then
t.Result.ToString "N0"
else
"n/a"
|> printfn "%10i %20O %14s" t.Id t.Status
// The example displays output like the following:
// Waiting for the first 10 tasks to complete...
// Status of tasks:
//
// Task Id Status Iterations
// 1 RanToCompletion 2,000,000
// 2 RanToCompletion 2,000,000
// 3 RanToCompletion 2,000,000
// 4 RanToCompletion 2,000,000
// 5 RanToCompletion 2,000,000
// 6 RanToCompletion 2,000,000
// 7 RanToCompletion 2,000,000
// 8 RanToCompletion 2,000,000
// 9 RanToCompletion 2,000,000
// 10 Canceled n/a
// 11 Canceled n/a
// 12 Canceled n/a
// 13 Canceled n/a
// 14 Canceled n/a
// 15 Canceled n/a
// 16 RanToCompletion 2,000,000
// 17 Canceled n/a
// 18 Canceled n/a
// 19 Canceled n/a
// 20 Canceled n/a
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim tasks As New List(Of Task(Of Integer))()
Dim source As New CancellationTokenSource
Dim token As CancellationToken = source.Token
Dim completedIterations As Integer = 0
For n As Integer = 0 To 19
tasks.Add(Task.Run( Function()
Dim iterations As Integer= 0
For ctr As Long = 1 To 2000000
token.ThrowIfCancellationRequested()
iterations += 1
Next
Interlocked.Increment(completedIterations)
If completedIterations >= 10 Then source.Cancel()
Return iterations
End Function, token))
Next
Console.WriteLine("Waiting for the first 10 tasks to complete... ")
Try
Task.WaitAll(tasks.ToArray())
Catch e As AggregateException
Console.WriteLine("Status of tasks:")
Console.WriteLine()
Console.WriteLine("{0,10} {1,20} {2,14}", "Task Id",
"Status", "Iterations")
For Each t In tasks
Console.WriteLine("{0,10} {1,20} {2,14}",
t.Id, t.Status,
If(t.Status <> TaskStatus.Canceled,
t.Result.ToString("N0"), "n/a"))
Next
End Try
End Sub
End Module
' The example displays output like the following:
' Waiting for the first 10 tasks to complete...
' Status of tasks:
'
' Task Id Status Iterations
' 1 RanToCompletion 2,000,000
' 2 RanToCompletion 2,000,000
' 3 RanToCompletion 2,000,000
' 4 RanToCompletion 2,000,000
' 5 RanToCompletion 2,000,000
' 6 RanToCompletion 2,000,000
' 7 RanToCompletion 2,000,000
' 8 RanToCompletion 2,000,000
' 9 RanToCompletion 2,000,000
' 10 Canceled n/a
' 11 Canceled n/a
' 12 Canceled n/a
' 13 Canceled n/a
' 14 Canceled n/a
' 15 Canceled n/a
' 16 RanToCompletion 2,000,000
' 17 Canceled n/a
' 18 Canceled n/a
' 19 Canceled n/a
' 20 Canceled n/a
该示例循环访问所有任务,而不是使用 InnerExceptions 属性检查异常,以确定哪些任务已成功完成,哪些任务已取消。 对于已完成的任务,它将显示任务返回的值。
由于取消是协作的,因此每个任务都可以决定如何响应取消。 以下示例与第一个示例类似,不同之处在于,取消令牌后,任务将返回已完成的迭代次数,而不是引发异常。
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
var tasks = new List<Task<int>>();
var source = new CancellationTokenSource();
var token = source.Token;
int completedIterations = 0;
for (int n = 0; n <= 19; n++)
tasks.Add(Task.Run( () => { int iterations = 0;
for (int ctr = 1; ctr <= 2000000; ctr++) {
if (token.IsCancellationRequested)
return iterations;
iterations++;
}
Interlocked.Increment(ref completedIterations);
if (completedIterations >= 10)
source.Cancel();
return iterations; }, token));
Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
try {
Task.WaitAll(tasks.ToArray());
}
catch (AggregateException) {
Console.WriteLine("Status of tasks:\n");
Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
"Status", "Iterations");
foreach (var t in tasks)
Console.WriteLine("{0,10} {1,20} {2,14}",
t.Id, t.Status,
t.Status != TaskStatus.Canceled ? t.Result.ToString("N0") : "n/a");
}
}
}
// The example displays output like the following:
// Status of tasks:
//
// Task Id Status Iterations
// 1 RanToCompletion 2,000,000
// 2 RanToCompletion 2,000,000
// 3 RanToCompletion 2,000,000
// 4 RanToCompletion 2,000,000
// 5 RanToCompletion 2,000,000
// 6 RanToCompletion 2,000,000
// 7 RanToCompletion 2,000,000
// 8 RanToCompletion 2,000,000
// 9 RanToCompletion 2,000,000
// 10 RanToCompletion 1,658,326
// 11 RanToCompletion 1,988,506
// 12 RanToCompletion 2,000,000
// 13 RanToCompletion 1,942,246
// 14 RanToCompletion 950,108
// 15 RanToCompletion 1,837,832
// 16 RanToCompletion 1,687,182
// 17 RanToCompletion 194,548
// 18 Canceled Not Started
// 19 Canceled Not Started
// 20 Canceled Not Started
open System
open System.Collections.Generic
open System.Threading
open System.Threading.Tasks
let source = new CancellationTokenSource()
let token = source.Token
let mutable completedIterations = 0
let tasks =
[| for _ = 0 to 19 do
Task.Run(
(fun () ->
let mutable iterations = 0
for _ = 1 to 2000000 do
token.ThrowIfCancellationRequested()
iterations <- iterations + 1
Interlocked.Increment &completedIterations |> ignore
if completedIterations >= 10 then
source.Cancel()
iterations),
token
) |]
printfn "Waiting for the first 10 tasks to complete...\n"
try
tasks |> Seq.cast |> Array.ofSeq |> Task.WaitAll
with :? AggregateException ->
printfn "Status of tasks:\n"
printfn "%10s %20s %14s" "Task Id" "Status" "Iterations"
for t in tasks do
if t.Status <> TaskStatus.Canceled then
t.Result.ToString "N0"
else
"n/a"
|> printfn "%10i %20O %14s" t.Id t.Status
// The example displays output like the following:
// Status of tasks:
//
// Task Id Status Iterations
// 1 RanToCompletion 2,000,000
// 2 RanToCompletion 2,000,000
// 3 RanToCompletion 2,000,000
// 4 RanToCompletion 2,000,000
// 5 RanToCompletion 2,000,000
// 6 RanToCompletion 2,000,000
// 7 RanToCompletion 2,000,000
// 8 RanToCompletion 2,000,000
// 9 RanToCompletion 2,000,000
// 10 RanToCompletion 1,658,326
// 11 RanToCompletion 1,988,506
// 12 RanToCompletion 2,000,000
// 13 RanToCompletion 1,942,246
// 14 RanToCompletion 950,108
// 15 RanToCompletion 1,837,832
// 16 RanToCompletion 1,687,182
// 17 RanToCompletion 194,548
// 18 Canceled Not Started
// 19 Canceled Not Started
// 20 Canceled Not Started
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim tasks As New List(Of Task(Of Integer))()
Dim source As New CancellationTokenSource
Dim token As CancellationToken = source.Token
Dim completedIterations As Integer = 0
For n As Integer = 0 To 19
tasks.Add(Task.Run( Function()
Dim iterations As Integer= 0
For ctr As Long = 1 To 2000000
If token.IsCancellationRequested Then
Return iterations
End If
iterations += 1
Next
Interlocked.Increment(completedIterations)
If completedIterations >= 10 Then source.Cancel()
Return iterations
End Function, token))
Next
Try
Task.WaitAll(tasks.ToArray())
Catch e As AggregateException
Console.WriteLine("Status of tasks:")
Console.WriteLine()
Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
"Status", "Iterations")
For Each t In tasks
Console.WriteLine("{0,10} {1,20} {2,14}",
t.Id, t.Status,
If(t.Status <> TaskStatus.Canceled,
t.Result.ToString("N0"), "Not Started"))
Next
End Try
End Sub
End Module
' The example displays output like the following:
' Status of tasks:
'
' Task Id Status Iterations
' 1 RanToCompletion 2,000,000
' 2 RanToCompletion 2,000,000
' 3 RanToCompletion 2,000,000
' 4 RanToCompletion 2,000,000
' 5 RanToCompletion 2,000,000
' 6 RanToCompletion 2,000,000
' 7 RanToCompletion 2,000,000
' 8 RanToCompletion 2,000,000
' 9 RanToCompletion 2,000,000
' 10 RanToCompletion 1,658,326
' 11 RanToCompletion 1,988,506
' 12 RanToCompletion 2,000,000
' 13 RanToCompletion 1,942,246
' 14 RanToCompletion 950,108
' 15 RanToCompletion 1,837,832
' 16 RanToCompletion 1,687,182
' 17 RanToCompletion 194,548
' 18 Canceled Not Started
' 19 Canceled Not Started
' 20 Canceled Not Started
该示例仍必须处理异常 AggregateException ,因为请求取消时尚未启动的任何任务仍会引发异常。
注解
如果在任务开始执行之前请求取消,则不会执行该任务。 而是将其设置为 Canceled 状态并引发 TaskCanceledException 异常。
方法 Run 是 方法的更简单替代 StartNew 方法。 它创建具有以下默认值的任务:
它使用默认的任务计划程序。
有关处理任务操作引发的异常的信息,请参阅 异常处理。
另请参阅
适用于
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈