Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task Parallel Library - LongRunning task vs Multiple Continuations

I'm researching the usage of the Task Parallel Library for a work project I'm doing and want to understand the advantages/disadvantages of long running tasks. I haven't got a real-life example yet, just want to understand the theory behind this.

From what the MSDN pages say about task schedulers and this SO question, it would seem as though it is best to avoid long-running tasks as much as possible so that you are not creating threads outside of the ThreadPool. But say you did have a task which was going to take a long time to complete, instead of this:

Task.Factory.StartNew(() => DoTimeConsumingWork(), TaskCreationOptions.LongRunning)

Could you try and split up your work into smaller, quicker units of work and use task continuations, like this:

Task.Factory
    .StartNew(() => DoWorkPart1())
    .ContinueWith(t => DoWorkPart2())
    .ContinueWith(t => DoWorkPart3())
    //...etc

Would this approach be any more beneficial or is it overkill for what it is trying to achieve?

like image 693
Peter Monks Avatar asked Jan 30 '12 11:01

Peter Monks


2 Answers

it would seem as though it is best to avoid long-running tasks as much as possible

Not entirely correct. If you need it then you will have to make/allocate a thread somehow and then the Task with LongRunning option is probably the best choice. The flag simply informs the scheduler the Task might take a while so that the scheduler can anticipate. It might even ignore the option.

Could you try and split up your work into smaller, quicker units of work a

If you can, then do it. But not al taks are so easily separated.

like image 85
Henk Holterman Avatar answered Nov 16 '22 05:11

Henk Holterman


When you specify TaskCreationOptions.LongRunning mostly it assigns a dedicated thread from outside of thread pool.

I would suggest simply go for BackgroundWorker class which makes sure your long running task will be ran on a separate dedicated thread instead of a thread from thread pool

like image 4
Haris Hasan Avatar answered Nov 16 '22 03:11

Haris Hasan