When I schedule a lot of tasks, and some tasks go into delay mode, I would expect others to start running, but the following code demonstrates that this does not happen.
I limited the MaxDegreeOfParallelism
to 3, you can see that a new group of 3 tasks is activated only after the first 3 are finished, although it was possible to start them immediately when the first three entered the delay.
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var s = new Stopwatch();
s.Start();
Parallel.For(1, 12, new ParallelOptions() { MaxDegreeOfParallelism = 3 }, (i) =>
{
Debug.WriteLine($"Task: {i}, Elapsed: {s.Elapsed}");
Task.WaitAll(Task.Delay(5000));
});
}
}
}
Output:
Task: 4, Elapsed: 00:00:00.0811475
Task: 1, Elapsed: 00:00:00.0811470
Task: 7, Elapsed: 00:00:00.0811479
Task: 2, Elapsed: 00:00:05.0972314
Task: 8, Elapsed: 00:00:05.1036003
Task: 5, Elapsed: 00:00:05.1036003
Task: 9, Elapsed: 00:00:10.1058859
Task: 3, Elapsed: 00:00:10.1101862
Task: 6, Elapsed: 00:00:10.1356772
Task: 10, Elapsed: 00:00:15.1183184
Task: 11, Elapsed: 00:00:20.1289868
The same output is obtained in both TargetFramework net48
and TargetFramework netcoreapp3.1
.
How is it possible to make that when some of the tasks are in sleep or delay mode then others will come into action?
As far as I know, Windows behaves with threads, that when one sleeps, Windows switches to run another thread. Similarly, I also need tasks.
Maybe I should work with something else and not tasks? Maybe with threads? But how exactly?
To summarize what I need:
- Run many actions at the same time and according to the turn.
- Possibility to limit the operations to X operations at the same time.
- In the event that one operation enters standby or sleep mode, another can start or continue work.
- When an action finishes the sleep period it returns to work according to the turn as a new action that never started.