详细介绍.NET并行与多线程学习基础
程序员文章站
2022-04-21 20:31:01
...
一、并行初试:
public static void test() { for (int i = 0; i < 10000; i++) { Console.WriteLine(i); } } public static void test1() { for (int i = 0; i < 10000; i++) { Console.WriteLine(i + "aaaaaaaaaaaaaaa"); } }
调用:
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); //串行执行: test(); test1(); //并行执行: 17Parallel.Invoke(test, test1); 19sw.Stop(); 21Console.WriteLine("共耗费时间:"); 23Console.WriteLine(sw.ElapsedMilliseconds / 1000+"s"); }
二、分区并行:
Parallel.ForEach(Partitioner.Create(1,20,5),(x,s)=>{ //并行代码中自定义串行,第三个参数表示item1到item2之间的范围 Console.WriteLine(x); for (int i = x.Item1; i < x.Item2; i++) { if (i == 10) break; Console.WriteLine(i); } s.Break();// 非常类似普通for循环中的break if (s.ShouldExitCurrentIteration) return; });
三、异常捕获:AggregateException
int[] arry = new int[10001]; for (int i = 0; i < 10000; i++) { arry[i] = i; } try { Parallel.ForEach(arry, (x, s) => { Console.WriteLine(x); if (sw.Elapsed.Seconds > 3) { throw new TimeoutException("操作超时"); } }); } catch (AggregateException ex) { foreach (var item in ex.InnerExceptions) { Console.WriteLine(item); } }
四、指定并行调度:
ParallelOptions options = new ParallelOptions(); options.MaxDegreeOfParallelism = 1;//如果设置为1就类似于串行代码按顺序执行 options.MaxDegreeOfParallelism =Environment.ProcessorCount;//获取计算机上面的处理器数量 Parallel.For(1,10,options,(x) => { Console.WriteLine(x); });
以上就是详细介绍.NET并行与多线程学习基础的详细内容,更多请关注其它相关文章!