C#线程池ThreadPool.QueueUserWorkItem接收线程执行的方法返回值

  最近在项目中需要用到多线程,考虑了一番,选择了ThreadPool,我的需求是要拿到线程执行方法的返回值,

但是ThreadPool.QueueUserWorkItem的回调方法默认是没有返回值的,搜了搜,都是简单介绍ThreadPool.QueueUserWorkItem的各种

用法,只能自己想办法了。

  回调方法不带返回值,迂回一下,回调方法用对象的方法,返回值放在对象的属性中,在对象方法执行时将需要的返回值赋值给对应属性。

等所有线程执行完,循环对象列表,取回返回值,然后想怎么处理返回值就OK了。上代码: 

  封装对象:

 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     }

  多线程调用:

 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 }
原文地址:https://www.cnblogs.com/yetiea/p/3361925.html