最近在项目中须要用到多线程,考虑了一番,选择了ThreadPool,个人需求是要拿到线程执行方法的返回值,多线程
可是ThreadPool.QueueUserWorkItem的回调方法默认是没有返回值的,搜了搜,都是简单介绍ThreadPool.QueueUserWorkItem的各类spa
用法,只能本身想办法了。线程
回调方法不带返回值,迂回一下,回调方法用对象的方法,返回值放在对象的属性中,在对象方法执行时将须要的返回值赋值给对应属性。code
等全部线程执行完,循环对象列表,取回返回值,而后想怎么处理返回值就OK了。上代码: 对象
封装对象:blog
1 using System; 2 using System.Threading; 3 public class ThreadReturnData 4 { 5 public ManualResetEvent manual; 6 public string res; 7 8 public void ReturnThreadData(object obj) 9 { 10 //线程耗时操做方法 11 res = DoSomething(obj); 12 manual.Set(); 13 } 14 }
多线程调用:string
1 List<ThreadReturnData> testList = new List<ThreadReturnData>(); 2 IList<ManualResetEvent> arrManual = new List<ManualResetEvent>(); 3 for (int i = 0; i < i; i++) 4 { 5 ThreadReturnData temp = new ThreadReturnData(); 6 temp.manual = new ManualResetEvent(false); 7 arrManual.Add(temp.manual); 8 ThreadPool.QueueUserWorkItem(new WaitCallback(temp.ReturnThreadData), i); 9 testList.Add(temp); 10 } 11 } 12 if (arrManual.Count > 0) 13 { 14 ////等待全部线程执行完 15 WaitHandle.WaitAll(arrManual.ToArray()); 16 } 17 foreach (ThreadReturnData d in testList) 18 { 19 d.res; 20 //todo 21 }