I am trying to get my head around Task.WaitAll(..) in the Task Parallel Library.
I am running a test using the following code to try to simulate two tasks, one that will run longer (10 seconds) than the specified amount of time to wait for (10,, and one to run less (3 seconds) than the specified amount of time to wait for. The specified amount of time is 5 seconds. The code I am using is the following:
Task<int>[] tasks = new Task<int>[]
{
Task.Factory.StartNew<int>(()=>
{
Thread.Sleep(10000);
return 1;
}),
Task.Factory.StartNew<int>(()=>
{
Thread.Sleep(3000);
return 2;
})
};
TimeSpan timeSpan = new TimeSpan(0, 0, 5);
Task.WaitAll(tasks,timeSpan);
int[] results = new int[tasks.Length];
for(int i = 0; i < tasks.Length;i++)
{
Console.WriteLine(tasks[i].Result);
}
As far as the timeSpan, I have also tried directly passing in 5000 instead of the timeSpan variable, but it is not working. I am getting the following output:
1
2
I would expect to only get the following output because the other thread is executing longer than the expected amount of time to wait.
1
Am I misunderstanding this, or doing this test wrong?