C#异步编程
基于任务的异步模式 (TAP)
https://docs.microsoft.com/zh-cn/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Parallel_ForEach_Test
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
List<long> list = new List<long>();
for (int i = 50; i < 60; i++)
{
list.Add(i);
}
sw.Start();
List<double> list1 = new List<double>();
Parallel.ForEach(list,
currentElement =>
{
double sall2 = 0;
for (int g = 0; g < 10000000; g++)
{
double x = Convert.ToDouble(1 * currentElement);
double y = Convert.ToDouble(2);
double km = Math.Pow(x, y);
sall2 += km;
}
list1.Add(sall2);
});
list1.Sort();
for (int i = 0; i < list1.Count; i++)
{
Console.WriteLine(list1[i]);
}
//Parallel.ForEach(list1, item =>
//{
// Console.WriteLine(item);
//});
sw.Stop();
Console.WriteLine(string.Format("并行执行时间{0}毫秒", sw.ElapsedMilliseconds));
sw.Reset();
sw.Start();
List<double> list2 = new List<double>();
for (int j = 0; j < list.Count; j++)
{
double sall = 0;
for (int k = 0; k < 10000000; k++)
{
double x = Convert.ToDouble(1 * list[j]);
double y = Convert.ToDouble(2);
double km = Math.Pow(x, y);
sall += km;
}
list2.Add(sall);
}
list2.Sort();
for (int i = 0; i < list2.Count; i++)
{
Console.WriteLine(list2[i]);
}
sw.Stop();
Console.WriteLine(string.Format("同步执行时间{0}毫秒", sw.ElapsedMilliseconds));
Console.ReadKey();
}
}
}