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)
Type Parameters
The result type of the task.
Parameters ReturnsA Task(TResult)
that represents the work queued to execute in the thread pool.
The function
parameter is null
.
The task has been canceled. This exception is stored into the returned task.
The task has been canceled.
ExamplesThe following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. 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
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
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
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
The example still must handle the AggregateException exception, since any tasks that have not started when cancellation is requested still throw an exception.
RemarksIf cancellation is requested before the task begins execution, the task does not execute. Instead it is set to the Canceled state and throws a TaskCanceledException exception.
The Run method is a simpler alternative to the StartNew method. It creates a task with the following default values:
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.
See alsoRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4