My laptop has 2 logical processors, and I came across a scenario where, if I plan 2 tasks that take more than 1 second, without designating them long-term, subsequent tasks start in 1 second. Is it possible to change this timeout?
I know that ordinary tasks should be short - much shorter than a second, if possible - I'm just wondering if I see a hard-coded TPL behavior or if I can influence this behavior in any other way, it works.
This Console application method should demonstrate behavior for a machine with any number of processors:
static void Main(string[] args) { var timer = new Stopwatch(); timer.Start(); int numberOfTasks = Environment.ProcessorCount; var rudeTasks = new List<Task>(); var shortTasks = new List<Task>(); for (int index = 0; index < numberOfTasks; index++) { int capturedIndex = index; rudeTasks.Add(Task.Factory.StartNew(() => { Console.WriteLine("Starting rude task {0} at {1}ms", capturedIndex, timer.ElapsedMilliseconds); Thread.Sleep(5000); })); } for (int index = 0; index < numberOfTasks; index++) { int capturedIndex = index; shortTasks.Add(Task.Factory.StartNew(() => { Console.WriteLine("Short-running task {0} running at {1}ms", capturedIndex, timer.ElapsedMilliseconds); })); } Task.WaitAll(shortTasks.ToArray()); Console.WriteLine("Finished waiting for short tasks at {0}ms", timer.ElapsedMilliseconds); Task.WaitAll(rudeTasks.ToArray()); Console.WriteLine("Finished waiting for rude tasks at {0}ms", timer.ElapsedMilliseconds); Console.ReadLine(); }
Here is the output of the application on my 2-processor laptop:
Starting rude task 0 at 2ms Starting rude task 1 at 2ms Short-running task 0 running at 1002ms Short-running task 1 running at 1002ms Finished waiting for short tasks at 1002ms Finished waiting for rude tasks at 5004ms Press any key to continue . . .
Rows:
Short-running task 0 running at 1002ms Short-running task 1 running at 1002ms
indicate that there is a 1-second timeout or something similar that allows you to perform shorter tasks on "rough" tasks. This is what I am asking.
source share