I found some code that uses the Task.WaitAny condition.
Task<int>[] tasks = new Task<int>[3];
tasks[0] = Task.Run(() => { Thread.Sleep(2000); return 1; });
tasks[1] = Task.Run(() => { Thread.Sleep(1000); return 2; });
tasks[2] = Task.Run(() => { Thread.Sleep(3000); return 3; });
while (tasks.Length > 0) {
int i = Task.WaitAny(tasks);
Task<int> completedTask = tasks[i];
Console.WriteLine(completedTask.Result);
var temp = tasks.ToList();
temp.RemoveAt(i);
tasks = temp.ToArray();
}
The code works fine, the result is 2 1 3.
When I tried to change the sleeping intervals
tasks[0] = Task.Run(() => { Thread.Sleep(2000); return 1; });
tasks[1] = Task.Run(() => { Thread.Sleep(1000); return 2; });
tasks[2] = Task.Run(() => { Thread.Sleep(1000); return 3; });
while (tasks.Length > 0) {
int i = Task.WaitAny(tasks);
Task<int> completedTask = tasks[i];
Console.WriteLine(completedTask.Result);
var temp = tasks.ToList();
temp.RemoveAt(i);
tasks = temp.ToArray();
}
I got 1 2 3, despite task number two is the one with the smallest sleeping time and should be the one removed first.
What is happening under the hood?
Thread.Sleep is fairly accurate in pausing the program for the specified number of milliseconds.
Thread.Sleep(1000) means that task will be available for execution after 1000 millisecond.
But which task is to be execute first from all the available tasks is decided by task scheduler,it decide the order of execution of task based on number of threads in thread-pool and many other factors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With