C#:使用Parallel并行执行任务
1. 代码实现
class Program
{
static void Main(string[] args)
{
TestParallel();
Console.ReadKey();
} static void TestParallel()
{
List<Action> listTask = new List<Action>();
for (int i = ; i < ; i++)
{
listTask.Add(new Action(TestAction));
}
Parallel.For(, listTask.Count, new Action<int>(i => listTask[i].Invoke())); } static void TestAction()
{
string gid = Guid.NewGuid().ToString();
Console.WriteLine("当前线程ID:{0},线程启动....GID:{1}", Thread.CurrentThread.ManagedThreadId, gid);
Thread.Sleep();
Console.WriteLine("当前线程ID:{0},线程结束<<<<....GID:{1}", Thread.CurrentThread.ManagedThreadId, gid);
} }
2. 运行结果: