Parallel==Task+waitall (The main thread is also utilized, Task is improved)
Invoke()
Parallel.Invoke(() => this.DoSomethingLong("btnParallel_Click_0") , () => this.DoSomethingLong("btnParallel_Click_1") , () => this.DoSomethingLong("btnParallel_Click_2") , () => this.DoSomethingLong("btnParallel_Click_3") , () => this.DoSomethingLong("btnParallel_Click_4") , () => this.DoSomethingLong("btnParallel_Click_5"));
For()
1 Parallel.For(0, 5, t => this.DoSomethingLong($"btnParallel_Click_{t}"));
Foreach() (You can use ParallelOptions to set the maximum concurrent number)
1 Parallel.ForEach(new int[] { 1, 2, 3, 4, 5 }, t => this.DoSomethingLong($"btnParallel_Click_{t}"));
1 ParallelOptions option = new ParallelOptions() 2 { 3 MaxDegreeOfParallelism = 3//最大并发数 4 }; 5 Parallel.ForEach(new int[] { 1, 2, 3, 4, 5, 6 }, option, t => 6 { 7 this.DoSomethingLong($"btnParallel_Click_{t}"); 8 });
1 new Action(() => 2 { 3 ParallelOptions option = new ParallelOptions() 4 { 5 MaxDegreeOfParallelism = 3//最大并发数 6 }; 7 Parallel.ForEach(new int[] { 1, 2, 3, 4, 5, 6 }, option, t => 8 { 9 this.DoSomethingLong($"btnParallel_Click_{t}"); 10 }); 11 }).BeginInvoke(null, null);
Thread Break and Stop
1 ParallelOptions option = new ParallelOptions() 2 { 3 MaxDegreeOfParallelism = 3 // Maximum concurrency 4 }; 5 Parallel.ForEach( new int [] { 1 , 2 , 3 , 4 , 5 , 6 }, option, (t, state) => 6 { 7 this .DoSomethingLong($ " btnParallel_Click_{t} " ); 8 // state.Break(); // this time ends 9 //return; 10 11 state.Stop(); // The entire Parallel ends 12 return ; 13 // Cannot coexist 14 });