TPL(Task Parallel Library)多线程、并发功能

The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces. The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. 

上述为MSDN中关于TPL库的描述。通过以上描述可知,TPL的主要目的是通过简化应用中雨并行/并发相关逻辑的处理来提高软件开发人员的效率。

这里主要套路TPL库中有关Task和Parallel的用法。

1、构建Task数组

Task[] taskArray = new Task[3];

2、初始化数组成员(此处使用Factory)

taskArray[0] = Task.Factory.StartNew();
taskArray[1] = Task.Factory.StartNew();
taskArray[2] = Task.Factory.StartNew();

3、使用Parallel构建处理逻辑

Parallel.For(0, 5,
(i => Console.WriteLine(string.Format("print {0}.", i))));
Parallel.ForEach(items,
(i => Console.WriteLine(string.Format("print {0}.", i))));

4、等待所有任务完成

Task.WaitAll(taskArray);
原文地址:https://www.cnblogs.com/dadream/p/4260332.html