分类: C#

.NET 4.0 – Parallel task






最近重改之前别人写的一点程序,将一些process改为了多线程作业,做了点research,了解了一下C# 4以来的一个新的library,task parallel library. 这里作个简单的介绍

什么是task,为什么用task

The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces in the .NET Framework 4.0. The TPL scales the degree of concurrency dynamically to efficiently use all the cores that are available. By using TPL, you can maximize the performance of your code while focusing on the work that your program is designed to accomplish.

TPL 是.net framework 4.o 新的一个多线程作业的库,属于System.Threading and System.Threading.Tasks namespaces. task 在工作性能上比较旧的Thread,有大大的提高。主要在于其避免了之前的context switch(switch from thread to thread),特别是对于单核的处理器。反而 task parallel library 其实是利用了thread自身的功能,同步的在同一个thread下多线程作业。下面用一个例子,来表现这个区别:

Screen Shot 2013-05-18 at 4.06.48 PM

 

我们用一个thread , 和一个task 运行一个简单的程序,在consol 上输出结果:

Screen Shot 2013-05-18 at 4.05.58 PM

 

看看下面的运行结果。task的运行效率大大的超过thread.

简单的用下图说明下,之间的区别:

Screen Shot 2013-05-18 at 4.11.08 PM

 

上面是thread的运行方式,下面是task.

怎么用

建立:


var task = Task.Factory.StartNew(() => DoSomeWork());

等待task完成


//单一task

var task = Task.Factory.StartNew(() => DoSomeWork());

task.Wait();

//多项task

var task1 = Task.Factory.StartNew(() => DoSomeWork());

var task2 = Task.Factory.StartNew(() => DoSomeWork());

var task3 = Task.Factory.StartNew(() => DoSomeWork());

Task.WaitAll(task1, task2, task3);

连续性(task会在完成前一个task之后,继续下一个)


var task = Task.Factory.StartNew(() =>

{

Thread.Sleep(3000);

return "dummy value";

});

task.ContinueWith(t => Console.WriteLine(t.Result));


//多个task

var task1 = Task.Factory.StartNew(() =>

{

Thread.Sleep(3000);

return "dummy value 1";

});

 

var task2 = Task.Factory.StartNew(() =>

{

Thread.Sleep(3000);

return "dummy value 2";

});

 

var task3 = Task.Factory.StartNew(() =>

{

Thread.Sleep(3000);

return "dummy value 3";

});

 

Task.Factory.ContinueWhenAll(new[] { task1, task2, task3 }, tasks =>

{

foreach (Task<string> task in tasks)

{

Console.WriteLine(task.Result);

}

});

这里只是简单的作一个最基础的介绍,更多的运用,你可以去看看官方库的解释:

System.Threading.Tasks Namespace

Reference :

 




发表评论