标签:parallel
1,用Parallel.For()方法循环
class Program { static void Main(string[] args) { //=============================第一种 Parallel.For(0,//第一个参数:开始索引 10,//第二个参数:最大索引 (i, parallelLoopState) =>//第三个参数:循环委托方法 { Console.WriteLine("索引:{0},任务id:{1},线程id:{2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId); }); //=============================第二种 Parallel.For<string>(0,//第一个参数:开始索引 10,//第二个参数:最大索引 //第三个参数:线程开始的方法 () => { Console.WriteLine("线程开启:{0}", Thread.CurrentThread.ManagedThreadId); return "aa"; }, //第四个参数:循环委托方法 (i, pls, str1) => { Console.WriteLine("索引:{0},线程id:{1},任务id:{2}", i, Thread.CurrentThread.ManagedThreadId,Task.CurrentId); return "bb"; }, //第五个参数:线程结束的方法 str => Console.WriteLine("线程结束:{0}", Thread.CurrentThread.ManagedThreadId)); Console.ReadLine(); } }
2,用Parallel.ForEach()方法循环
class Program { static void Main(string[] args) { string[] data = new string[] { "1", "2", "3", "4" }; Parallel.ForEach(data, r => { Console.WriteLine(r); }); Parallel.ForEach<string>(data, (r, p, l) => { //r:遍历数组的值 //l:数组的索引 Console.WriteLine(r + "," + l); }); Console.ReadKey(); } }
3,用Parallel.ForEach()方法并行调用多个方法
class Program { static void Main(string[] args) { Parallel.Invoke(Foo, Bar); Console.ReadLine(); } private static void Foo() { Console.WriteLine("Foo; task:{0};threadis:{1}", Task.CurrentId, Thread.CurrentThread.ManagedThreadId); } private static void Bar() { Console.WriteLine("Bar; task:{0};threadis:{1}", Task.CurrentId, Thread.CurrentThread.ManagedThreadId); } }
本文出自 “程序猿的家--Hunter” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1608592
标签:parallel
原文地址:http://962410314.blog.51cto.com/7563109/1608592