Reputation: 63846
How to pass LongRunning flag specifically to Task.Run()? highlights that it can be a little messy to get Task creation flags into the newer APIs especially using the async
pattern.
And I found this article claiming it's not a great idea with async
anyway and shouldn't be used: http://blog.i3arnon.com/2015/07/02/task-run-long-running/
My understanding is that this flag in practice will cause TPL to spin up a dedicated thread rather than stressing the threadpool but particularly if my application doesn't involve lots of parallel tasks, is it really a big deal? Can I safely omit the flag if my expected parallelism is less that the default threadpool size (whatever that is) - is the worst that happens the threadpool might be starved of threads for a few hundred milliseconds anyway?
Upvotes: 4
Views: 2411
Reputation: 43996
The LongRunning
flag is omitted by default when calling the Task.Factory.StartNew
method without passing the TaskCreationOptions
argument, so you can safely assume that omiting it is safe. Actually it is more safe to omit it than to include it, since this flag is intended as a performance optimization technique, not as an everyday commodity.
In general, don't use it unless you find that you really need it. You'd typically only use
LongRunning
if you found through performance testing that not using it was causing long delays in the processing of other work. (citation)
In case that the ThreadPool
is routinely starved because its threads are misused (are blocked while waiting for I/O operations to complete), then instead of decorating all of your Task
s with the LongRunning
flag, a simpler and more efficient workaround could be to increase the minimum number of ThreadPool
threads with the method ThreadPool.SetMinThreads
during the initialization of your application. For example:
ThreadPool.SetMinThreads(workerThreads: 100, completionPortThreads: 5);
It will be easier to undo this hack when you refactor your application to use asynchrony correctly, instead of undoing the LongRunning
flag everywhere in your code.
Upvotes: 5
Reputation: 50752
The whole idea behind Thread Pool is that creating task take some milliseconds, because it asks OS to create it, switch contexts and so on and so on... so to deal with it, Framework create some pool, and keep used threads there for later use...
You are right, LongRunning flag most probably will cause new thread creation... this make sense when new task is going to take longer and Thread creation time is not significant in it.
Threadpool has certain algorithms, if you take lots of threads from there intensively and keep them busy, it may decide to double the amount of threads assuming that you are going to take more and more ... so if you are going to take threads from Thread Pool busy long enough, you will not get any benefit from ThreadPool, but instead you get some overhead.
So ignoring that flag will not break anything, but may bring some overheads.
Upvotes: 1