10

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?


  • It really depends on what you mean by long. - user703016

2 답변


5

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.


  • I agree that not all algorithms can be split up very easily into smaller chunks. But if you could, would it be better to do so? I'm guessing that it would utilize the TPL better than the scheduler creating another thread, am I correct? - Peter Monks
  • It might be better, but that's not certain. I usually wouldn't bother too much. You don't (can't) know if it leads to an extra thread. - Henk Holterman

3

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


  • TaskCreationOptions.LongRunning also usually causes a dedicated thread to be created. - dtb

Linked


Related

Latest