我试图想出一种方法来以最快的方式加速组合列表中包含的大量对象。希望利用 PLINQ 我尝试过,但这不是线程安全的解决方案。我在 4.0 和 4.5 的 VS2010 和 VS11Beta 中进行了测试。这是我的示例应用程序。如果您在 1-500 之间更改 BlowUp(),它通常会起作用。500 年后车轮脱离轨道。它会在多个地方失败。有谁知道解决这个问题的最快方法?(多维数组 + PLINQ?)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PLinqBlowsUp
{
class Program
{
static void Main(string[] args)
{
BlowUp(5000);
}
private static void BlowUp(int blowupNum)
{
try
{
var theExistingMasterListOfAllRowsOfData = new List<List<KeyValuePair<string, dynamic>>>();
//Add some test data
Enumerable.Range(0, blowupNum).AsParallel().ForAll(row => theExistingMasterListOfAllRowsOfData.Add(AddRowToMasterList(row)));
var aNewRowOfData = new List<KeyValuePair<string, dynamic>>();
//Add some test data
var column = new KeyValuePair<string, dynamic>("Title", "MyTitle");
aNewRowOfData.Add(column);
var anotherNewRowOfData = new List<KeyValuePair<string, dynamic>>();
//Add some test data
var columnA = new KeyValuePair<string, dynamic>("Date", DateTime.Now);
var columnB = new KeyValuePair<string, dynamic>("ImportantColumn", "ImportantData");
var columnC = new KeyValuePair<string, dynamic>("VeryImportantColumn", "VeryImportantData");
anotherNewRowOfData.Add(columnA);
anotherNewRowOfData.Add(columnB);
anotherNewRowOfData.Add(columnC);
//Now the Problem
aNewRowOfData.AsParallel().ForAll(anrod => theExistingMasterListOfAllRowsOfData.ForEach(temloarod => temloarod.Add(anrod)));
anotherNewRowOfData.AsParallel().ForAll(anrod => theExistingMasterListOfAllRowsOfData.ForEach(temloarod => temloarod.Add(anrod)));
//Test for number
foreach (var masterRow in theExistingMasterListOfAllRowsOfData)
{
if (masterRow.Count != 7)
throw new Exception("BLOW UP!!!");
}
}
catch (AggregateException ex)
{
Console.WriteLine(ex.Message);
}
}
private static List<KeyValuePair<string, dynamic>> AddRowToMasterList(int row)
{
var columnA = new KeyValuePair<string, dynamic>("FirstName", "John" + row.ToString());
var columnB = new KeyValuePair<string, dynamic>("LastName", "Smith" + row.ToString());
var columnC = new KeyValuePair<string, dynamic>("Ssn", 123456789 + (row*10));
var list = new List<KeyValuePair<string, dynamic>>();
list.Add(columnA);
list.Add(columnB);
list.Add(columnC);
return list;
}
}
}