C# Task.Parallel
此示例演示了使用多种语言构造实现并行循环的几种方法。
View Code
View Code

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 }
也有其他的循环
常用的几个方法:

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); } }
重复就是力量,数量堆死质量
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言