Parallel.For、Parallel.Foreach 的使用

 

以下為演示 Parallel.For 與 Parallel.ForEach 的用法


//產生測試資料
List<string> testData = new List<string>();
//產生10組亂數字串
for (int i = 0; i < 10; i++)
{
    testData.Add(RndChars(20));
}
foreach (var item in testData)
{
    Console.WriteLine(item);
}
Console.WriteLine();



//for語法
List<
string> resultData = new List<string>();
//找出 testData 中包含a 或 包含 abc的字串
for (int i = 0; i < testData.Count(); i++)
{
if (testData[i].Contains(“a”) || testData[i].Contains(“abc”))
{
resultData.Add(testData[
i]);
}
}
foreach (var item in resultData)
{
Console.WriteLine(item);
}
Console.WriteLine();

//Parallel.For語法
List<
string> resultData2 = new List<string>();
Parallel.For(0, testData.Count() - 1, (
i, loopState) =>
{
string data = testData[i];
if (data.Contains(“a”) || data.Contains(“abc”))
{
resultData2.Add(data);
}
});
foreach (var item in resultData)
{
Console.WriteLine(item);
}
Console.WriteLine();

//Parallel.ForEach語法
List<
string> resultData3 = new List<string>();
Parallel.ForEach(testData, (
item, loopState) =>
{
//string data = testData[i];
if (item.Contains(“a”) || item.Contains(“abc”))
{
resultData3.Add(
item);
}
});
foreach (var item in resultData)
{
Console.WriteLine(item);
}
Console.WriteLine();

//亂數產生n字元的字串
string RndChars(int n)
{
var characters = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789”;
char[] chars = new char[n];
for (int i = 0; i < n; i++)
{
chars[i] = characters[
new Random().Next(characters.Length)];
}
return new string(chars);
}