it is better not to use LongRunning option when I start such tasks, so that we will be able to leverage ThreadPool instead of creating thread per Task.
When you're running async
code, you should not specify LongRunning
. If you do, then (as of today's implementation), the thread pool will start a new thread just to run the first part of your async
code. As soon as your code yields at an await
, that new thread will be disposed and the rest of the code will run on regular thread pool threads. So, LongRunning
is usually counterproductive for async
code.
I have a blog post on why StartNew
is dangerous, and I (briefly) cover all of the TaskCreationOptions
in that post:
AttachedToParent shouldn't be used in async tasks, so that's out. DenyChildAttach should always be used with async tasks (hint: if you didn't already know that, then StartNew isn't the tool you need). DenyChildAttach is passed by Task.Run. HideScheduler might be useful in some really obscure scheduling scenarios but in general should be avoided for async tasks. That only leaves LongRunning and PreferFairness, which are both optimization hints that should only be specified after application profiling. I often see LongRunning misused in particular. In the vast majority of situations, the threadpool will adjust to any long-running task in 0.5 seconds - without the LongRunning flag. Most likely, you don't really need it.