我在 C# 中使用 Parallel.ForEach 编写了以下代码
internal class Program
{
private static void Main(string[] args)
{
var recordList = new List<string> {"1", "two", "three", "four", "five", "six"};
var result = new ConcurrentBag<ProcessedData>();
Parallel.ForEach<string, ProcessedData>(recordList, () => null //local init
, (record, state, index, localInit) => //body
{
Console.WriteLine($"Processing {record}");
var integerValue = record.Length;
var processedString = record + " Processed";
localInit = new ProcessedData
{
IntegerValue = integerValue,
StringValue = processedString
};
return localInit;
}, bodyResult => //local finally
{
Console.WriteLine($"Adding {bodyResult.StringValue}");
result.Add(bodyResult);
});
foreach (var item in result)
{
Console.WriteLine($"{item.StringValue}");
}
Console.ReadLine();
}
private sealed class ProcessedData
{
internal int IntegerValue { get; set; }
internal string StringValue { get; set; }
}
当我运行程序时,我希望控制台打印出来 “1个处理”,“2个处理”,“3个处理”,“4个处理”,“5个处理”,“6个处理”。但是,只有一些项目被处理了!!!
你知道代码出了什么问题吗?
最佳答案
finally 不会对集合中的每个项目运行该操作。如果您想对集合中的每个项目执行一些操作,这就是正文的用途。 init 和 finally 用于初始化和拆除每个工作线程的。所以您的打印输出告诉您在处理您的项目时使用了三个线程。
关于c# - 我对 Parallel.ForEach 做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51390668/