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来等待其他线程是否执行完毕,用法如下:
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(); } }
时间: 2024-10-12 04:39:03