text stringlengths 0 13.4k |
|---|
GoalKicker.com – .NET Framework Notes for Professionals |
133 |
foreach(var task in tasks) |
Console.WriteLine(task.Result); |
Section 42.11: Task: WaitAny |
var allTasks = Enumerable.Range(1, 5).Select(n => new Task<int>(() => n)).ToArray(); |
var pendingTasks = allTasks.ToArray(); |
foreach(var task in allTasks) task.Start(); |
while(pendingTasks.Length > 0) |
{ |
var finishedTask = pendingTasks[Task.WaitAny(pendingTasks)]; |
Console.WriteLine("Task {0} finished", finishedTask.Result); |
pendingTasks = pendingTasks.Except(new[] {finishedTask}).ToArray(); |
} |
Task.WaitAll(allTasks); |
Note: The final WaitAll is necessary becasue WaitAny does not cause exceptions to be observed. |
Section 42.12: Task: handling exceptions (using Wait) |
var task1 = Task.Run(() => |
{ |
Console.WriteLine("Task 1 code starting..."); |
throw new Exception("Oh no, exception from task 1!!"); |
}); |
var task2 = Task.Run(() => |
{ |
Console.WriteLine("Task 2 code starting..."); |
throw new Exception("Oh no, exception from task 2!!"); |
}); |
Console.WriteLine("Starting tasks..."); |
try |
{ |
Task.WaitAll(task1, task2); |
} |
catch(AggregateException ex) |
{ |
Console.WriteLine("Task(s) failed!"); |
foreach(var inner in ex.InnerExceptions) |
Console.WriteLine(inner.Message); |
} |
Console.WriteLine("Task 1 status is: " + task1.Status); //Faulted |
Console.WriteLine("Task 2 status is: " + task2.Status); //Faulted |
Section 42.13: Task: handling exceptions (without using Wait) |
var task1 = Task.Run(() => |
{ |
Console.WriteLine("Task 1 code starting..."); |
throw new Exception("Oh no, exception from task 1!!"); |
}); |
var task2 = Task.Run(() => |
GoalKicker.com – .NET Framework Notes for Professionals |
134 |
{ |
Console.WriteLine("Task 2 code starting..."); |
throw new Exception("Oh no, exception from task 2!!"); |
}); |
var tasks = new[] {task1, task2}; |
Console.WriteLine("Starting tasks..."); |
while(tasks.All(task => !task.IsCompleted)); |
foreach(var task in tasks) |
{ |
if(task.IsFaulted) |
Console.WriteLine("Task failed: " + |
task.Exception.InnerExceptions.First().Message); |
} |
Console.WriteLine("Task 1 status is: " + task1.Status); //Faulted |
Console.WriteLine("Task 2 status is: " + task2.Status); //Faulted |
Section 42.14: Task: cancelling using CancellationToken |
var cancellationTokenSource = new CancellationTokenSource(); |
var cancellationToken = cancellationTokenSource.Token; |
var task = new Task((state) => |
{ |
int i = 1; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.