Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task WaitAny condition

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?

like image 277
MaPi Avatar asked Nov 11 '22 20:11

MaPi


1 Answers

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.

like image 129
Krishnachandra Pandey Avatar answered Nov 14 '22 21:11

Krishnachandra Pandey