task code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; public class Example { public static void Main() { var qTasks = new List<Task< string >>(); var paralist = new List< int > { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; foreach ( var para in paralist) { //StartNew 只接受输入参数是object类型的Func var fun = new Func< object , string >( (pa) => { //pa 是Func的定义参数 Console.WriteLine( "para is {0}" , pa); //Thread.Sleep(new Random().Next(500, 3000)); int ipa = Convert.ToInt32(pa); int result = ipa * 5; return result.ToString(); } ); var task = Task.Factory.StartNew(fun, para); //para是传入参数 qTasks.Add(task); Console.WriteLine( " task id is {0}" , task.Id); } Task.WaitAll(qTasks.ToArray()); //等待所有线程执行完毕 //收集所有task返回的数据 foreach ( var task in qTasks) { if (task.Result != null ) { Console.WriteLine( "task id : {0} , result : {1} " , task.Id, task.Result); } } Console.ReadKey(); } } |
有时候会需要用到ManualResetEvent来等待其他线程是否执行完毕,用法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; public class Example { static ManualResetEvent manualEvent = new ManualResetEvent( false ); public static void Main() { manualEvent.Reset(); //等同于将initialState设置为false Console.WriteLine( "In main .." ); LongTimeFunc(); manualEvent.WaitOne(10000); Console.WriteLine( "wait thread finish..." ); Console.ReadKey(); } private static void LongTimeFunc() { //Thread 多数时候可以使用Task代替,此刻thread设置为STA,所以这么用 Thread thread = new Thread( new ParameterizedThreadStart(ExecuteFunc)); thread.SetApartmentState(ApartmentState.STA); thread.IsBackground = true ; thread.Start( "real parameters" ); //ExecuteFunc 函数从此处传入参数 } private static void ExecuteFunc( object obj) { //long time operation Thread.Sleep(2000); Console.WriteLine(obj.ToString()); manualEvent.Set(); } } |
分类:
C#
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· 对象命名为何需要避免'-er'和'-or'后缀
· JDK 24 发布,新特性解读!
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· SQL Server如何跟踪自动统计信息更新?