我正在并行调用一个慢速网络服务。一切都很好,直到我意识到我需要从服务中获取一些信息。但我不知道从哪里找回值(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/