c# 线程池多任务处理并返回值

先新建一个封装类 包含 manual和返回值 

 

using System;
using System.Threading;
public class ThreadReturnData
{
public ManualResetEvent manual;
public string res;

public void ReturnThreadData(object obj)
{
//操作方法
res = DoSomething(obj);
manual.Set();
}
}

 

//-------------------------------------------------------------------------------------------------

List<ThreadReturnData> testList = new List<ThreadReturnData>();
IList<ManualResetEvent> arrManual = new List<ManualResetEvent>();
for (int i = 0; i < i; i++)
{
ThreadReturnData temp = new ThreadReturnData();
temp.manual = new ManualResetEvent(false);
arrManual.Add(temp.manual);
ThreadPool.QueueUserWorkItem(new WaitCallback(temp.ReturnThreadData), i);
testList.Add(temp);
}
}
if (arrManual.Count > 0)
{
////等待所有线程执行完
WaitHandle.WaitAll(arrManual.ToArray());
}
foreach (ThreadReturnData d in testList)
{
d.res;
//dowork
}

posted @ 2021-03-12 10:17  上海-天浩  阅读(808)  评论(0编辑  收藏  举报

Living in ShangHai

Copyright © 2008 天浩阁 Corporation, All Rights Reserved