C# Task.Parallel
作者:互联网
此示例演示了使用多种语言构造实现并行循环的几种方法。
1 using System.Threading.Tasks; 2 class Test 3 { 4 static int N = 1000; 5 6 static void TestMethod() 7 { 8 // Using a named method. 9 Parallel.For(0, N, Method2); 10 11 // Using an anonymous method. 12 Parallel.For(0, N, delegate(int i) 13 { 14 // Do Work. 15 }); 16 17 // Using a lambda expression. 18 Parallel.For(0, N, i => 19 { 20 // Do Work. 21 }); 22 } 23 24 static void Method2(int i) 25 { 26 // Do work. 27 } 28 }View Code
也有其他的循环
常用的几个方法:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; class ParallelInvokeDemo { // Demonstrated features: // Parallel.Invoke() // Expected results: // The threads on which each task gets executed may be different. // The thread assignments may be different in different executions. // The tasks may get executed in any order. // Documentation: // http://msdn.microsoft.com/library/dd783942(VS.100).aspx static void Main() { try { Parallel.Invoke( BasicAction, // Param #0 - static method () => // Param #1 - lambda expression { Console.WriteLine("Method=beta, Thread={0}", Thread.CurrentThread.ManagedThreadId); }, delegate() // Param #2 - in-line delegate { Console.WriteLine("Method=gamma, Thread={0}", Thread.CurrentThread.ManagedThreadId); } ); } // No exception is expected in this example, but if one is still thrown from a task, // it will be wrapped in AggregateException and propagated to the main thread. catch (AggregateException e) { Console.WriteLine("An action has thrown an exception. THIS WAS UNEXPECTED.\n{0}", e.InnerException.ToString()); } } static void BasicAction() { Console.WriteLine("Method=alpha, Thread={0}", Thread.CurrentThread.ManagedThreadId); } }View Code
标签:Task,迭代,C#,并行,IEnumerable,循环,Func,Action,Parallel 来源: https://www.cnblogs.com/HomeSapiens/p/16379937.html