gpt4 book ai didi

c# - 如何并行运行一组函数并等待完成后的结果?

转载 作者:太空狗 更新时间:2023-10-30 00:21:44 27 4
gpt4 key购买 nike

我需要同时异步运行一组繁重的函数并将结果填充到列表中。这是伪代码:

List<TResult> results = new List<TResults>();
List<Func<T, TResult>> tasks = PopulateTasks();

foreach(var task in tasks)
{
// Run Logic in question
1. Run each task asynchronously/parallely
2. Put the results in the results list upon each task completion
}

Console.WriteLine("All tasks completed and results populated");

我需要 foreach block 中的逻辑。你们能帮帮我吗?

我有一些限制:解决方案必须符合 .net 3.5(不是 .net 4,但出于我的知识目的,将不胜感激 .net 4 替代解决方案)

提前致谢。

最佳答案

一个简单的 3.5 实现看起来像这样

List<TResult> results = new List<TResults>();
List<Func<T, TResult>> tasks = PopulateTasks();

ManualResetEvent waitHandle = new ManualResetEvent(false);
void RunTasks()
{
int i = 0;
foreach(var task in tasks)
{
int captured = i++;
ThreadPool.QueueUserWorkItem(state => RunTask(task, captured))
}

waitHandle.WaitOne();

Console.WriteLine("All tasks completed and results populated");
}

private int counter;
private readonly object listLock = new object();
void RunTask(Func<T, TResult> task, int index)
{
var res = task(...); //You haven't specified where the parameter comes from
lock (listLock )
{
results[index] = res;
}
if (InterLocked.Increment(ref counter) == tasks.Count)
waitHandle.Set();
}

关于c# - 如何并行运行一组函数并等待完成后的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4068971/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com