C#4并行计算

时间:2024-05-29 08:35:44
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Parallel.For(, ,
i => Console.WriteLine("The square of {0} is {1}", i, i * i)); const int maxValues = ;
int[] squares = new int[maxValues]; Parallel.For(, maxValues,
i => squares[i] = i * i); for (var i = ; i < maxValues; i++)
{
Console.WriteLine(squares[i]);
} Console.WriteLine("==========================================");
string[] words = new string[] { "We", "hold", "there", "to", "be", "self-evident" }; Parallel.ForEach(words,
i => Console.WriteLine($"{i} has {i.Length}"));//和For的区别是:For需要索引号,ForEach不需要 /*
The square of 0 is 0
The square of 6 is 36
The square of 5 is 25
The square of 1 is 1
The square of 4 is 16
The square of 13 is 169
The square of 3 is 9
The square of 11 is 121
The square of 12 is 144
The square of 14 is 196
The square of 2 is 4
The square of 8 is 64
The square of 10 is 100
The square of 9 is 81
The square of 7 is 49
0
1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
400
441
484
529
576
625
676
729
784
841
900
961
1024
1089
1156
1225
1296
1369
1444
1521
1600
1681
1764
1849
1936
2025
2116
2209
2304
2401
==========================================
We has 2
self-evident has 12
to has 2
there has 5
hold has 4
be has 2
请按任意键继续. . . */
}
}
}