views:

79

answers:

2

I came across this comprehensive explanation of the new .NET TPL library recently, and it sounded pretty impressive. Having read the article, it appears that the new taskmanager is so clever it can even tell whether your parallel tasks would be faster if done serially on the same thread, rather than be parcelled out to worker threads. This could often be a difficult decision.

Having written a lot of code using what threading was available previously, it now seems as though everything ought to be written with tasks, which would hand over a lot of the work to the taskmanager.

Am I right in thinking that whatever I previously did with threads should now be done with tasks? Of course there will always be cases where you need fine control, but should one generally throw ordinary background work onto a task, rather than a new thread? Ie has the default "I need this to run in the background => new thread" become "new task" instead?

+2  A: 

Basically, yes, you want to use tasks and let them take care of the thread use. In practice, the tasks are processed by a thread pool.

Steven Sudit
To clarify, IIRC, in .net 4, they are processed by the *new* ThreadPool implementation from the TPL team.
BioBuckyBall
@Lucas: Thanks for pointing out that this isn't the same old pool.
Steven Sudit
And you can override, you can say that the task is long running, which will spin up a new thread just for that task. In other words, you get all the benefits of the new TPL *and* the old thread class.
Lasse V. Karlsen
Tasks are processed by the TaskScheduler. The default scheduler uses the threadpool, but there's also a scheduler for running tasks on the GUI thread and you could provide your own, which does something completely different.
Brian Rasmussen
@Brian: Yes, there are various ways to tune the process, including the degree of concurrency and the partitioning technique. It's surprisingly flexible.
Steven Sudit
+1  A: 

Tasks are managed by the TaskScheduler. The default TaskScheduler runs tasks on ThreadPool threads and as such you have the same issues as you normally would when using the ThreadPool: It is hard to control the setup (priority, locale, background/foreground, etc.) on threads in the pool. If you need to control any of these aspects it may be better to manage the threads yourself. You may also implement your own scheduler to handle some of these issues.

For most other parts the new Task class works very well.

Brian Rasmussen