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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With