Parallel并发执行多个任务 多线程的,主线程会参与计算---阻塞界面等于TaskWaitAll+主线程计算
常用方法
1、Invoke 尽可能并行执行提供的每个操作
1 Console.WriteLine("***************Parallel.Invoke Start******************"); 2 Parallel.Invoke( 3 () => Console.WriteLine("action0"), 4 () => Console.WriteLine("action1"), 5 () => Console.WriteLine("action2"), 6 () => Console.WriteLine("action3"), 7 () => Console.WriteLine("action4"), 8 () => Console.WriteLine("action5"), 9 () => Console.WriteLine("action6")); 10 Console.WriteLine("***************Parallel.Invoke End******************"); 11 Console.WriteLine();
2、For 并行运行迭代,可以配置循环选项,可以监视和操作循环的状态
1 Console.WriteLine("***************Parallel.For Start******************"); 2 Parallel.For(0, 5, i => Console.WriteLine($"Parallel.For{i}")); 3 Parallel.For(0, 5, (i,p) => Console.WriteLine($"Parallel.For{i} {p.IsExceptional}")); 4 Console.WriteLine("***************Parallel.For End******************"); 5 Console.WriteLine();
3、Foreach 并行运行迭代,可以配置循环选项,可以监视和操作循环的状态
1 var array = new[] { "A", "B", "C", "D", "E" }; 2 Console.WriteLine("***************Parallel.ForEach Start******************"); 3 Parallel.ForEach(array, s => Console.WriteLine(s)); 4 Console.WriteLine("***************Parallel.ForEach End******************"); 5 Console.WriteLine();
有没有办法不阻塞主线程?结合Task
1 Task.Run(() => 2 { 3 ParallelOptions options = new ParallelOptions(); 4 options.MaxDegreeOfParallelism = 3; 5 Parallel.For(0, 10, options, s => Console.WriteLine(s)); 6 });
微软文档:
Parallel:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.parallel?view=netframework-4.8
ParallelOptions:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.paralleloptions?view=netframework-4.8