一、描述
数据和任务的并行库,并行的同步操作
二、使用方式
1、Parallel.Invoke
参数为Action的可变参数数组,异步的执行每一个Actionn
using System.Net;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Action ac = () =>
{
Console.WriteLine(string.Format("Current Thread is :{0}", Thread.CurrentThread.ManagedThreadId));
};
Console.WriteLine("Main");
Parallel.Invoke(ac, ac, ac);
Console.WriteLine("Main End");
}
}
2、Parallel.For
并行执行循环,参数是初始值,结束值,Action<int>内部的值是当前的序列
using System.Net;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Console.WriteLine("Start");
Parallel.For(0, 10, async (index) =>
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
});
Console.WriteLine("Finsihed");
}
}
3、Parallel.ForEach
并行循环,参数是:数组,Action<T> 数组的值
using System.Net;
using System.Threading.Tasks;
class Program
{
static void Main()
{
int[] values = { 1, 2, 3, 4, 5, 6, 7 };
Parallel.ForEach(values, (value) =>
{
Console.WriteLine(value);
});
}
}
留言