Task.Run メソッド
定義
ThreadPool 上で実行する指定された作業をキューに配置し、その作業のタスクまたは Task<TResult> のハンドルを戻します。Queues the specified work to run on the ThreadPool and returns a task or Task<TResult> handle for that work.
オーバーロード
Run(Action) |
スレッド プール上で実行する指定された作業をキューに配置し、その作業を表す Task オブジェクトを戻します。Queues the specified work to run on the thread pool and returns a Task object that represents that work. |
Run(Func<Task>) |
スレッド プール上で実行する作業を指定してキューに配置し、 |
Run(Action, CancellationToken) |
スレッド プール上で実行する指定された作業をキューに配置し、その作業を表す Task オブジェクトを戻します。Queues the specified work to run on the thread pool and returns a Task object that represents that work. まだ開始されていない場合、キャンセル トークンで処理をキャンセルできます。A cancellation token allows the work to be cancelled if it has not yet started. |
Run(Func<Task>, CancellationToken) |
スレッド プール上で実行する作業を指定してキューに配置し、 |
Run<TResult>(Func<TResult>, CancellationToken) |
スレッド プール上で実行する指定された作業をキューに配置し、その作業を表す |
Run<TResult>(Func<Task<TResult>>, CancellationToken) |
スレッド プール上で実行する指定された作業をキューに配置し、 |
Run<TResult>(Func<TResult>) |
スレッド プール上で実行する指定された作業をキューに配置し、その作業を表す Task<TResult> オブジェクトを戻します。Queues the specified work to run on the thread pool and returns a Task<TResult> object that represents that work. まだ開始されていない場合、キャンセル トークンで処理をキャンセルできます。A cancellation token allows the work to be cancelled if it has not yet started. |
Run<TResult>(Func<Task<TResult>>) |
スレッド プール上で実行する指定された作業をキューに配置し、 |
注釈
メソッドには、 Run 既定値を使用してタスクを簡単に開始できるようにする一連のオーバーロードが用意されています。The Run method provides a set of overloads that make it easy to start a task by using default values. オーバーロードに代わる軽量の方法です StartNew 。It is a lightweight alternative to the StartNew overloads.
Run(Action)
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
非同期的に実行する処理The work to execute asynchronously
戻り値
ThreadPool で実行するためにキューに配置された作業を表すタスク。A task that represents the work queued to execute in the ThreadPool.
例外
action
パラメーターは null
でした。The action
parameter was null
.
例
次の例では、 ShowThreadInfo
現在のスレッドのを表示するメソッドを定義して Thread.ManagedThreadId います。The following example defines a ShowThreadInfo
method that displays the Thread.ManagedThreadId of the current thread. これはアプリケーションスレッドから直接呼び出され、 Action メソッドに渡されたデリゲートから呼び出され Run(Action) ます。It is called directly from the application thread, and is called from the Action delegate passed to the Run(Action) method.
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
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
次の例は前の例と似ていますが、ラムダ式を使用して、タスクが実行するコードを定義している点が異なります。The following example is similar to the previous one, except that it uses a lambda expression to define the code that the task is to execute.
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
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
この例は、非同期タスクがメインアプリケーションスレッドとは異なるスレッドで実行されることを示しています。The examples show that the asynchronous task executes on a different thread than the main application thread.
メソッドの呼び出しに Wait よって、タスクが完了し、アプリケーションが終了する前にその出力が表示されます。The call to the Wait method ensures that the task completes and displays its output before the application ends. それ以外の場合は、 Main
タスクが終了する前にメソッドが完了する可能性があります。Otherwise, it is possible that the Main
method will complete before the task finishes.
次の例は、メソッドを示してい Run(Action) ます。The following example illustrates the Run(Action) method. ディレクトリ名の配列を定義し、各ディレクトリ内のファイル名を取得するための別のタスクを開始します。It defines an array of directory names and starts a separate task to retrieve the file names in each directory. すべてのタスクは、ファイル名を1つのオブジェクトに書き込み ConcurrentBag<T> ます。All tasks write the file names to a single ConcurrentBag<T> object. 次に、メソッドを呼び出して、 WaitAll(Task[]) すべてのタスクが完了したことを確認した後、オブジェクトに書き込まれたファイル名の総数を表示し ConcurrentBag<T> ます。The example then calls the WaitAll(Task[]) method to ensure that all tasks have completed, and then displays a count of the total number of file names written to the ConcurrentBag<T> object.
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)
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メソッドを使用すると、1回のメソッド呼び出しでタスクを作成および実行できます。これは、メソッドの代わりに、より簡単な方法です StartNew 。The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method. 次の既定値を使用してタスクを作成します。It creates a task with the following default values:
そのキャンセルトークンは CancellationToken.None です。Its cancellation token is CancellationToken.None.
CreationOptionsプロパティ値が TaskCreationOptions.DenyChildAttach です。Its CreationOptions property value is TaskCreationOptions.DenyChildAttach.
既定のタスクスケジューラを使用します。It uses the default task scheduler.
タスク操作によってスローされる例外の処理の詳細については、「 例外処理」を参照してください。For information on handling exceptions thrown by task operations, see Exception Handling.
こちらもご覧ください
適用対象
Run(Func<Task>)
スレッド プール上で実行する作業を指定してキューに配置し、function
によって返されるタスクのプロキシを返します。Queues the specified work to run on the thread pool and returns a proxy for the task returned by 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
によって返されるタスクのプロキシを表すタスク。A task that represents a proxy for the task returned by function
.
例外
function
パラメーターは null
でした。The function
parameter was null
.
注釈
タスク操作によってスローされる例外の処理の詳細については、「 例外処理」を参照してください。For information on handling exceptions thrown by task operations, see Exception Handling.
こちらもご覧ください
適用対象
Run(Action, CancellationToken)
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
非同期的に実行する処理The work to execute asynchronously
- cancellationToken
- CancellationToken
まだ開始されていない場合、処理を取り消すために使用できるキャンセル トークン。A cancellation token that can be used to cancel the work if it has not yet started. Run(Action, CancellationToken) により cancellationToken
が action
に渡されません。Run(Action, CancellationToken) does not pass cancellationToken
to action
.
戻り値
スレッド プールで実行するためにキューに配置された作業を表すタスク。A task that represents the work queued to execute in the thread pool.
例外
action
パラメーターは null
でした。The action
parameter was null
.
タスクが取り消されました。The task has been canceled.
cancellationToken
に関連付けられた CancellationTokenSource が破棄されました。The CancellationTokenSource associated with cancellationToken
was disposed.
例
次の例では、メソッドを呼び出し Run(Action, CancellationToken) て、C:\Windows\System32 ディレクトリ内のファイルを反復処理するタスクを作成します。The following example calls the Run(Action, CancellationToken) method to create a task that iterates the files in the C:\Windows\System32 directory. ラムダ式は、メソッドを呼び出して、 Parallel.ForEach 各ファイルに関する情報をオブジェクトに追加 List<T> します。The lambda expression calls the Parallel.ForEach method to add information about each file to a List<T> object. ループによって呼び出された、デタッチされた入れ子になった各タスクは、 Parallel.ForEach キャンセルトークンの状態をチェックし、キャンセルが要求された場合はメソッドを呼び出し CancellationToken.ThrowIfCancellationRequested ます。Each detached nested task invoked by the Parallel.ForEach loop checks the state of the cancellation token and, if cancellation is requested, calls the CancellationToken.ThrowIfCancellationRequested method. メソッドは、 CancellationToken.ThrowIfCancellationRequested OperationCanceledException catch
呼び出し元のスレッドがメソッドを呼び出したときに、ブロックで処理される例外をスローし Task.Wait ます。The CancellationToken.ThrowIfCancellationRequested method throws an OperationCanceledException exception that is handled in a catch
block when the calling thread calls the Task.Wait method.
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
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
注釈
タスクが実行を開始する前にキャンセルが要求された場合、タスクは実行されません。If cancellation is requested before the task begins execution, the task does not execute. 代わりに、状態に設定され、 Canceled 例外をスローし TaskCanceledException ます。Instead it is set to the Canceled state and throws a TaskCanceledException exception.
メソッドは、メソッドの Run(Action, CancellationToken) 代わりに、より簡単な方法です TaskFactory.StartNew(Action, CancellationToken) 。The Run(Action, CancellationToken) method is a simpler alternative to the TaskFactory.StartNew(Action, CancellationToken) method. 次の既定値を使用してタスクを作成します。It creates a task with the following default values:
CreationOptionsプロパティ値が TaskCreationOptions.DenyChildAttach です。Its CreationOptions property value is TaskCreationOptions.DenyChildAttach.
既定のタスクスケジューラを使用します。It uses the default task scheduler.
タスク操作によってスローされる例外の処理の詳細については、「 例外処理」を参照してください。For information on handling exceptions thrown by task operations, see Exception Handling.
こちらもご覧ください
適用対象
Run(Func<Task>, CancellationToken)
スレッド プール上で実行する作業を指定してキューに配置し、function
によって返されるタスクのプロキシを返します。Queues the specified work to run on the thread pool and returns a proxy for the task returned by function
. まだ開始されていない場合、キャンセル トークンで処理をキャンセルできます。A cancellation token allows the work to be cancelled if it has not yet started.
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
まだ開始されていない場合、処理を取り消すために使用できるキャンセル トークン。A cancellation token that can be used to cancel the work if it has not yet started. Run(Func<Task>, CancellationToken) により cancellationToken
が action
に渡されません。Run(Func<Task>, CancellationToken) does not pass cancellationToken
to action
.
戻り値
function
によって返されるタスクのプロキシを表すタスク。A task that represents a proxy for the task returned by function
.
例外
function
パラメーターは null
でした。The function
parameter was null
.
タスクが取り消されました。The task has been canceled.
cancellationToken
に関連付けられた CancellationTokenSource が破棄されました。The CancellationTokenSource associated with cancellationToken
was disposed.
注釈
タスク操作によってスローされる例外の処理の詳細については、「 例外処理」を参照してください。For information on handling exceptions thrown by task operations, see Exception Handling.
こちらもご覧ください
適用対象
Run<TResult>(Func<TResult>, CancellationToken)
スレッド プール上で実行する指定された作業をキューに配置し、その作業を表す Task(TResult)
オブジェクトを戻します。Queues the specified work to run on the thread pool and returns a Task(TResult)
object that represents that work.
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
タスクの結果の型。The result type of the task.
パラメーター
- function
- Func<TResult>
非同期的に実行する処理The work to execute asynchronously
- cancellationToken
- CancellationToken
まだ開始されていない場合、処理を取り消すために使用できるキャンセル トークン。A cancellation token that can be used to cancel the work if it has not yet started. Run<TResult>(Func<TResult>, CancellationToken) により cancellationToken
が action
に渡されません。Run<TResult>(Func<TResult>, CancellationToken) does not pass cancellationToken
to action
.
戻り値
Task(TResult)
は、スレッド プールで実行するためにキューに配置された作業を表します。A Task(TResult)
that represents the work queued to execute in the thread pool.
例外
function
パラメーターが null
です。The function
parameter is null
.
タスクが取り消されました。The task has been canceled.
cancellationToken
に関連付けられた CancellationTokenSource が破棄されました。The CancellationTokenSource associated with cancellationToken
was disposed.
例
次の例では、カウンターが200万の値にインクリメントされるまでループするタスクを20個作成します。The following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. 最初の10個のタスクが200万に達した場合、キャンセルトークンは取り消され、カウンターが200万に達していないすべてのタスクは取り消されます。When the first 10 tasks reach 2 million, the cancellation token is cancelled, and any tasks whose counters have not reached 2 million are cancelled. この例は、考えられる出力を示しています。The example shows possible output.
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
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 正常に完了し、取り消されたものを特定します。Instead of using the InnerExceptions property to examine exceptions, the example iterates all tasks to determine which have completed successfully and which have been cancelled. 完了したものについては、タスクによって返された値が表示されます。For those that have completed, it displays the value returned by the task.
取り消しは協調しているため、各タスクはキャンセルに応答する方法を決定できます。Because cancellation is cooperative, each task can decide how to respond to cancellation. 次の例は最初の例と似ていますが、トークンが取り消されると、タスクは、例外をスローするのではなく、完了したイテレーションの数を返します。The following example is like the first, except that, once the token is cancelled, tasks return the number of iterations they've completed rather than throw an exception.
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
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キャンセルが要求されたときに開始されていないタスクも例外をスローするため、この例では引き続き例外を処理する必要があります。The example still must handle the AggregateException exception, since any tasks that have not started when cancellation is requested still throw an exception.
注釈
タスクが実行を開始する前にキャンセルが要求された場合、タスクは実行されません。If cancellation is requested before the task begins execution, the task does not execute. 代わりに、状態に設定され、 Canceled 例外をスローし TaskCanceledException ます。Instead it is set to the Canceled state and throws a TaskCanceledException exception.
メソッドは、メソッドの Run 代わりに、より簡単な方法です StartNew 。The Run method is a simpler alternative to the StartNew method. 次の既定値を使用してタスクを作成します。It creates a task with the following default values:
CreationOptionsプロパティ値が TaskCreationOptions.DenyChildAttach です。Its CreationOptions property value is TaskCreationOptions.DenyChildAttach.
既定のタスクスケジューラを使用します。It uses the default task scheduler.
タスク操作によってスローされる例外の処理の詳細については、「 例外処理」を参照してください。For information on handling exceptions thrown by task operations, see Exception Handling.
こちらもご覧ください
適用対象
Run<TResult>(Func<Task<TResult>>, CancellationToken)
スレッド プール上で実行する指定された作業をキューに配置し、function
によって返される Task(TResult)
のプロキシを返します。Queues the specified work to run on the thread pool and returns a proxy for the Task(TResult)
returned by function
.
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
プロキシ タスクによって返される結果の型。The type of the result returned by the proxy task.
パラメーター
- cancellationToken
- CancellationToken
まだ開始されていない場合、処理を取り消すために使用できるキャンセル トークン。A cancellation token that can be used to cancel the work if it has not yet started. Run<TResult>(Func<Task<TResult>>, CancellationToken) により cancellationToken
が action
に渡されません。Run<TResult>(Func<Task<TResult>>, CancellationToken) does not pass cancellationToken
to action
.
戻り値
Task(TResult)
によって返される Task(TResult)
のプロキシを表す function
。A Task(TResult)
that represents a proxy for the Task(TResult)
returned by function
.
例外
function
パラメーターは null
でした。The function
parameter was null
.
タスクが取り消されました。The task has been canceled.
cancellationToken
に関連付けられた CancellationTokenSource が破棄されました。The CancellationTokenSource associated with cancellationToken
was disposed.
注釈
タスク操作によってスローされる例外の処理の詳細については、「 例外処理」を参照してください。For information on handling exceptions thrown by task operations, see Exception Handling.
こちらもご覧ください
適用対象
Run<TResult>(Func<TResult>)
スレッド プール上で実行する指定された作業をキューに配置し、その作業を表す Task<TResult> オブジェクトを戻します。Queues the specified work to run on the thread pool and returns a Task<TResult> object that represents that work. まだ開始されていない場合、キャンセル トークンで処理をキャンセルできます。A cancellation token allows the work to be cancelled if it has not yet started.
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
タスクの戻り値の型。The return type of the task.
パラメーター
- function
- Func<TResult>
非同期的に実行する処理。The work to execute asynchronously.
戻り値
スレッド プールで実行するためキューに配置された処理を表すタスク オブジェクト。A task object that represents the work queued to execute in the thread pool.
例外
function
パラメーターが null
です。The function
parameter 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. WaitAll(Task[])メソッドは、すべてのタスクが完了したことを確認するために呼び出されます。The WaitAll(Task[]) method is called to ensure that all tasks have completed before displaying the word count of each book to the console.
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
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+
0 個以上の区切り文字の後に1つ以上の空白文字が続くパターンに一致します。The regular expression \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.
注釈
メソッドは、メソッドの Run 代わりに、より簡単な方法です TaskFactory.StartNew(Action) 。The Run method is a simpler alternative to the TaskFactory.StartNew(Action) method. 次の既定値を使用してタスクを作成します。It creates a task with the following default values:
そのキャンセルトークンは CancellationToken.None です。Its cancellation token is CancellationToken.None.
CreationOptionsプロパティ値が TaskCreationOptions.DenyChildAttach です。Its CreationOptions property value is TaskCreationOptions.DenyChildAttach.
既定のタスクスケジューラを使用します。It uses the default task scheduler.
タスク操作によってスローされる例外の処理の詳細については、「 例外処理」を参照してください。For information on handling exceptions thrown by task operations, see Exception Handling.
こちらもご覧ください
適用対象
Run<TResult>(Func<Task<TResult>>)
スレッド プール上で実行する指定された作業をキューに配置し、function
によって返される Task(TResult)
のプロキシを返します。Queues the specified work to run on the thread pool and returns a proxy for the Task(TResult)
returned by function
. まだ開始されていない場合、キャンセル トークンで処理をキャンセルできます。A cancellation token allows the work to be cancelled if it has not yet started.
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
プロキシ タスクによって返される結果の型。The type of the result returned by the proxy task.
パラメーター
戻り値
Task(TResult)
によって返される Task(TResult)
のプロキシを表す function
。A Task(TResult)
that represents a proxy for the Task(TResult)
returned by function
.
例外
function
パラメーターは null
でした。The function
parameter was null
.
注釈
タスク操作によってスローされる例外の処理の詳細については、「 例外処理」を参照してください。For information on handling exceptions thrown by task operations, see Exception Handling.