如何运行一组功能的并行,等待完成后的结果?功能、结果、完成后

由网友(墨染青衣颜)分享简介:我有一个要求,运行一组沉重的异步功能在Sametime和填充结果列表。这里是伪$ C $下这样的:I have a requirement to run a set of heavy functions asynchronously at sametime and populate the results in a...

我有一个要求,运行一组沉重的异步功能在Sametime和填充结果列表。这里是伪$ C $下这样的:

I have a requirement to run a set of heavy functions asynchronously at sametime and populate the results in a list. Here is the pseudo code for this :

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 博克内部的逻辑。你们能plz帮助我吗?

I need the logic inside the foreach bock. Can you guys plz help me?

我有一些约束:该解决方案必须在.NET 3.5兼容的(而不是.NET 4,但.NET 4替代解决方案将AP preciated为我所知的目的)

I have some constraint : The solution must be .net 3.5 compliant (not .net 4, but a .net 4 alternative solution would be appreciated for my knowledge purpose)

在此先感谢。

推荐答案

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

A simple 3.5 implementation could look like this

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();
}
阅读全文

相关推荐

最新文章