如何从Parallel.ForEach收集返回值? [英] How do I collect return values from Parallel.ForEach?
问题描述
我正在同时调用慢速网络服务。一切都很棒,直到我意识到我需要从服务中获取一些信息。但是我看不到在哪里找回价值。我无法写入数据库HttpContext。在使用Parallel.ForEach
I'm calling a slow webservice in parallel. Things were great until I realized I need to get some information back from the service. But I don't see where to get the values back. I can't write to the database, HttpContext.Current appears to be null inside of a method called using Parallel.ForEach
的方法中,Current似乎为空,下面是一个示例程序(在您看来,请想象一个缓慢的Web服务而不是字符串连接)
Below is a sample program (in your mind, please imagine a slow web service instead of a string concatenation)
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));
您可能想要类似的东西,
You probably want something like,
ParallelLoopResult result = Parallel.ForEach(words, word =>
{
string result = AddB(word);
// do something with result
});
如果您想在此末尾进行某种收藏,请考虑使用 System.Collections.Concurrent
,例如 ConcurrentBag
If you want some sort of collection at the end of this, consider using one of the collections under System.Collections.Concurrent
, like ConcurrentBag
ConcurrentBag<string> resultCollection = new ConcurrentBag<string>();
ParallelLoopResult result = Parallel.ForEach(words, word =>
{
resultCollection.Add(AddB(word));
});
// Do something with the result
这篇关于如何从Parallel.ForEach收集返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!