本文整理汇总了C#中System.Threading.Tasks.Task.WaitAll方法的典型用法代码示例。如果您正苦于以下问题:C# Task.WaitAll方法的具体用法?C# Task.WaitAll怎么用?C# Task.WaitAll使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Tasks.Task
的用法示例。
在下文中一共展示了Task.WaitAll方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
class Example
{
static void Main()
{
var tasks = new List<Task<int>>();
// Define a delegate that prints and returns the system tick count
Func<object, int> action = (object obj) =>
{
int i = (int)obj;
// Make each thread sleep a different time in order to return a different tick count
Thread.Sleep(i * 100);
// The tasks that receive an argument between 2 and 5 throw exceptions
if (2 <= i && i <= 5)
{
throw new InvalidOperationException("SIMULATED EXCEPTION");
}
int tickCount = Environment.TickCount;
Console.WriteLine("Task={0}, i={1}, TickCount={2}, Thread={3}", Task.CurrentId, i, tickCount, Thread.CurrentThread.ManagedThreadId);
return tickCount;
};
// Construct started tasks
for (int i = 0; i < 10; i++)
{
int index = i;
tasks.Add(Task<int>.Factory.StartNew(action, index));
}
try
{
// Wait for all the tasks to finish.
Task.WaitAll(tasks.ToArray());
// We should never get to this point
Console.WriteLine("WaitAll() has not thrown exceptions. THIS WAS NOT EXPECTED.");
}
catch (AggregateException e)
{
Console.WriteLine("\nThe following exceptions have been thrown by WaitAll(): (THIS WAS EXPECTED)");
for (int j = 0; j < e.InnerExceptions.Count; j++)
{
Console.WriteLine("\n-------------------------------------------------\n{0}", e.InnerExceptions[j].ToString());
}
}
}
}
输出:
Task=1, i=0, TickCount=1203822250, Thread=3 Task=2, i=1, TickCount=1203822359, Thread=4 Task=7, i=6, TickCount=1203823484, Thread=3 Task=8, i=7, TickCount=1203823890, Thread=4 Task=9, i=8, TickCount=1203824296, Thread=3 Task=10, i=9, TickCount=1203824796, Thread=4 The following exceptions have been thrown by WaitAll(): (THIS WAS EXPECTED) ------------------------------------------------- System.InvalidOperationException: SIMULATED EXCEPTION at Example.b__0(Object obj) at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() ------------------------------------------------- System.InvalidOperationException: SIMULATED EXCEPTION at Example. b__0(Object obj) at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() ------------------------------------------------- System.InvalidOperationException: SIMULATED EXCEPTION at Example. b__0(Object obj) at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() ------------------------------------------------- System.InvalidOperationException: SIMULATED EXCEPTION at Example. b__0(Object obj) at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute()