1

我有一个创建 4 个任务的 for 循环,每个任务都会打印其循环索引 - 用于测试性能的简单程序

我有一个运行上述循环 1000 次(迭代)的外部循环我想检查任务和线程的性能

(1) 测试 1:我认为这只会创建任务(不是线程),但我发现它使用 TPL

tasks[i] = Task.Factory.StartNew(() => Console.WriteLine(tmp));

(2)我用TaskCreationOptions.LongRunning重写如下

tasks[i] = Task.Factory.StartNew(() => Console.WriteLine(tmp), TaskCreationOptions.LongRunning);

(3) 然后我尝试使用与上面相同的代码测试线程不是任务,但现在使用“新线程”而不是工厂

for (int i = 0; i < 4; i++)
{
    var tmp = i;
    tasks[i] = new Thread(new ThreadStart(() => Console.WriteLine(tmp)));
    tasks[i].Start();
    tasks[i].Join();
}

时序结果显示最佳性能是 (2),然后是 (3),然后是 (1)

请解释一下性能结果的原因,并解释上面哪一个真正只是一个任务(一个OS进程),哪些正在使用线程?

我尝试使用探查器,但只能访问 Visual Studio 2010 Professional,而且探查器似乎仅随 permium 或 Ultimate 版本提供。

4

2 回答 2

1
Task.Factory.StartNew(

使用 ThreadPool 中的线程

LongRunning意味着,每个任务都应该创建自己的线程,因为它运行时间很长,我们不想干涸池

最后一个选项只是创建线程。

您是否检查了每种情况的内存使用情况?

于 2013-01-29T21:07:28.953 回答
0

Using Console.WriteLine as the action for testing perfomance in this case is pointless. Under the hood in all of your cases a new thread is spawn or reused from the pool for each iteration. This is a relatively costly thing to do. That means, as long as your operation is trivial, the overhead of the thread spawn or reuse costs will always compromise your performance test a lot.

And if your having a real, non-trivial operation going on in your threads, the spawn cost differences between your cases won´t matter anymore. In addition to that, you have very little control when using Task when and if a new thread is created or one from the pool is reused, which is always a good thing btw. My advice is, use Tasks when you have the need to process something in the background and leave the headache stuff to the framework.

I hope this is understandable.

And, for practical purposes, if you have big lists of things to compute and want to make use of multicore cpus you could also take a look at Parallel.Foreach or other things provided by the TPL.

Edit: Parallel.Foreach and the likes will decide for themselves if and when to spawn new threads. Using this methods will give you a maximum of flexibility because the runtime will decide for you, depending on the processor count, size of the list, etc. if its making sense to create new threads or if the overhead would be bigger as the gain.

于 2013-01-29T21:36:30.590 回答