标签:
Parallel类
Parallel类是对线程的一个很好抽象。该类位于System.Threading.Tasks命名空间中,提供了数据和任务并行性。
1.用Parallel.For()方法循环
//// simple scenario ParallelLoopResult result = Parallel.For(0, 10, async i => { Console.WriteLine("{0}, task: {1}, thread: {2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId); await Task.Delay(10); Console.WriteLine("{0}, task: {1}, thread: {2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine("is completed: {0}", result.IsCompleted);
2.提前停止Parallel.For
For()方法的一个重载版本接受第三个Action<int, ParallelLoopState>类型的参数。使用这些参数定义一个方法,就可以调用ParallelLoopState的Break()或Stop()方法,以影响循环结果。
// breaking early ParallelLoopResult result = Parallel.For(10, 40, (int i, ParallelLoopState pls) => { Console.WriteLine("i: {0} task {1}", i, Task.CurrentId); Thread.Sleep(10); if (i > 15) pls.Break(); }); Console.WriteLine("Is completed: {0}", result.IsCompleted); if (!result.IsCompleted) Console.WriteLine("lowest break iteration: {0}", result.LowestBreakIteration);
3.使用Parallel.ForEach()方法循环
string[] data = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve" }; ParallelLoopResult result = Parallel.ForEach<string>(data, s => { Console.WriteLine(s); }); Parallel.ForEach<string>(data, (s, pls, l) => { Console.WriteLine("{0} {1}", s, l); });
4.通过Parallel.Invoke()方法调用多个方法
static void ParallelInvoke() { Parallel.Invoke(Foo, Bar); } static void Foo() { Console.WriteLine("foo"); } static void Bar() { Console.WriteLine("bar"); }
推荐阅读:改善C#程序的建议10:用Parallel简化Task
标签:
原文地址:http://www.cnblogs.com/hmliang/p/5398285.html