System.Threading

System.Threading.Tasks.Parallel

Parallel

For

  1. public static void Main()
  2. {
  3. var rnd = new Random();
  4. int breakIndex = rnd.Next(1, 11);
  5. Console.WriteLine($"Will call Break at iteration {breakIndex}\n");
  6. var result = Parallel.For(1, 101, (i, state) =>
  7. {
  8. Console.WriteLine($"Beginning iteration {i}");
  9. int delay;
  10. lock (rnd)
  11. delay = rnd.Next(1, 1001);
  12. Thread.Sleep(delay);
  13. if (state.ShouldExitCurrentIteration)
  14. {
  15. if (state.LowestBreakIteration < i)
  16. return;
  17. }
  18. if (i == breakIndex)
  19. {
  20. Console.WriteLine($"Break in iteration {i}");
  21. state.Break();
  22. }
  23. Console.WriteLine($"Completed iteration {i}");
  24. });
  25. if (result.LowestBreakIteration.HasValue)
  26. Console.WriteLine($"\nLowest Break Iteration: {result.LowestBreakIteration}");
  27. else
  28. Console.WriteLine($"\nNo lowest break iteration.");
  29. }

ForEach

Invoke,执行多个方法

  • 方法允许同时调用不同的方法
  1. static void Main()
  2. {
  3. try
  4. {
  5. Parallel.Invoke(
  6. BasicAction, // Param #0 - static method
  7. () => // Param #1 - lambda expression
  8. {
  9. Console.WriteLine("Method=beta, Thread={0}", Thread.CurrentThread.ManagedThreadId);
  10. },
  11. delegate() // Param #2 - in-line delegate
  12. {
  13. Console.WriteLine("Method=gamma, Thread={0}", Thread.CurrentThread.ManagedThreadId);
  14. }
  15. );
  16. }
  17. // No exception is expected in this example, but if one is still thrown from a task,
  18. // it will be wrapped in AggregateException and propagated to the main thread.
  19. catch (AggregateException e)
  20. {
  21. Console.WriteLine("An action has thrown an exception. THIS WAS UNEXPECTED.\n{0}", e.InnerException.ToString());
  22. }
  23. }

thread pool