I have a code base using ThreadPool.QueueUserWorkItem
in several places. I thought it would be a good idea to switch from using ThreadPool.QueueUserWorkItem
to using Task.Factory.StartNew
with TaskScheduler.Default
as a scheduler.
After upgrading, I saw execution times of the application to sky high. It as an online transnational application, receiving requests and typically responding between 40ms and 500ms which is acceptable. After the switch to the Tasks way, I see many transactions taking from 4000ms to even 38000ms to respond which is unacceptable.
The flow is pretty complex. It involves a synchronous loop for the incoming transactions, which actually does the simple validations and insert to the database. After that, some parallel actions are fired, and the main loop continues to the next incoming transaction. The parallel actions are mainly logging, and a db intensive quality check of the data.
All logging actions were initiated in the ThreadPool with
ThreadPool.QueueUserWorkItem(/*logging action*/)
The quality check action was initiated with
Task.Factory.StartNew(/*qc action*/,
TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness)
After applying the changes The logging actions were switched to
Task.Factory.StartNew(/*logging action*/,
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default)
And the quality check action was switched to
Task.Factory.StartNew(/*qc action*/,
CancellationToken.None,
TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness,
TaskScheduler.Default)
Is there a possibility that the logging actions are stalling the quality check action when executed with Task.Factory.StartNew on the ThreadPoolScheduler (TaskScheduler.Default) but when executed directly on ThreadPool with QueueUserWorkItem, they don't?
Is there a possibility that the TaskCreationOptions.PreferFairness
flag in the quality check action, makes quality check wait for the logging actions even when this flag is not set in their initiation?