Parallel 类并行任务(仅仅当执行耗时操作时,才有必要使用)

时间:2023-03-09 01:01:56
Parallel 类并行任务(仅仅当执行耗时操作时,才有必要使用)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start(); ////非并行任务,总耗时间:3000
//Thread.Sleep(1000);
//Thread.Sleep(2000); ////并行任务,总耗时间:2000
//Parallel.Invoke(() =>
//{
// Thread.Sleep(1000);
//}, () =>
//{
// Thread.Sleep(2000);
//}); List<int> list = new List<int>();
var len = ;
object _olock = new object();
var count = ; //用户计算大于5000数的个数
for (int i = ; i < ; i++)
{
list.Add(i);
}
len = list.Count; Parallel.For(, len, (i) =>
{
lock (_olock)
{
//耗时操作
Thread.Sleep();
if (i > )
{
count++;
}
}
}); sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); Console.Read();
}
}
}

参考博客:https://www.cnblogs.com/ricky-wang/p/7003162.html