System.Threading
System.Threading.Tasks.Parallel
Parallel
For
public static void Main()
{
var rnd = new Random();
int breakIndex = rnd.Next(1, 11);
Console.WriteLine($"Will call Break at iteration {breakIndex}\n");
var result = Parallel.For(1, 101, (i, state) =>
{
Console.WriteLine($"Beginning iteration {i}");
int delay;
lock (rnd)
delay = rnd.Next(1, 1001);
Thread.Sleep(delay);
if (state.ShouldExitCurrentIteration)
{
if (state.LowestBreakIteration < i)
return;
}
if (i == breakIndex)
{
Console.WriteLine($"Break in iteration {i}");
state.Break();
}
Console.WriteLine($"Completed iteration {i}");
});
if (result.LowestBreakIteration.HasValue)
Console.WriteLine($"\nLowest Break Iteration: {result.LowestBreakIteration}");
else
Console.WriteLine($"\nNo lowest break iteration.");
}
ForEach
Invoke,执行多个方法
static void Main()
{
try
{
Parallel.Invoke(
BasicAction, // Param #0 - static method
() => // Param #1 - lambda expression
{
Console.WriteLine("Method=beta, Thread={0}", Thread.CurrentThread.ManagedThreadId);
},
delegate() // Param #2 - in-line delegate
{
Console.WriteLine("Method=gamma, Thread={0}", Thread.CurrentThread.ManagedThreadId);
}
);
}
// No exception is expected in this example, but if one is still thrown from a task,
// it will be wrapped in AggregateException and propagated to the main thread.
catch (AggregateException e)
{
Console.WriteLine("An action has thrown an exception. THIS WAS UNEXPECTED.\n{0}", e.InnerException.ToString());
}
}
thread pool