c# - 如何从 Parallel.ForEach 收集返回值?

标签 c# c#-4.0 parallel.foreach

我正在并行调用一个慢速网络服务。一切都很好,直到我意识到我需要从服务中获取一些信息。但我不知道从哪里找回值(value)。我无法写入数据库,在使用 Parallel.ForEach 调用的方法中,HttpContext.Current 似乎为空

下面是一个示例程序(在你的脑海中,请想象一个慢速的网络服务而不是字符串连接)

using System;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        WordMaker m = new WordMaker();
        m.MakeIt();
    }
    public class WordMaker
    {
        public void MakeIt()
        {
            string[] words = { "ack", "ook" };
            ParallelLoopResult result = Parallel.ForEach(words, word => AddB(word));
            Console.WriteLine("Where did my results go?");
            Console.ReadKey();
        }
        public string AddB(string word)
        {
            return "b" + word;
        }
    }

}

最佳答案

你在这里丢弃了它。

ParallelLoopResult result = Parallel.ForEach(words, word => AddB(word));

你可能想要这样的东西,

ParallelLoopResult result = Parallel.ForEach(words, word =>
{
    string result = AddB(word);
    // do something with result
});

如果你想在最后使用某种集合,请考虑使用 System.Collections.Concurrent 下的集合之一,例如 ConcurrentBag

ConcurrentBag<string> resultCollection = new ConcurrentBag<string>();
ParallelLoopResult result = Parallel.ForEach(words, word =>
{
    resultCollection.Add(AddB(word));
});

// Do something with the result

关于c# - 如何从 Parallel.ForEach 收集返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12610868/

相关文章:

c# - 添加具有数据类型属性的新 XElement

c# - 下层调用者是否能够从使用 C# 4.0 生成的程序集中的可选参数中获益?

.net - 将字节复制到 double 组中

c# - 任务调度程序中的手动线程与 Parallel.Foreach

c# - 使用 Parallel 在 C# 中优化文件搜索

c# - 如何在不使用环境枚举的情况下在 C# 中以编程方式解析环境变量?

c# - 在测试项目中使用 ASP.NET Core 的 ConfigurationBuilder

c# - Azure Function 对 Newtonsoft 11.0.2 和 Docker 容器的硬依赖

c# - 我可以延长 session 或实例或控制GC的生命周期吗?

.net - 如何取消任何当前的 Parallel.ForEach 并重新开始