Reputation: 12341
I'm experiencing a strange issue in a console application (unsure if this has something to do with it) and using Tasks.
Most examples show purposely invoking an Exception to test/explain the concept of WaitAll - but in my case, it seems I'm doing something fundamentally wrong (or don't fully understand).
Task<int> task1 = Task<int>.Factory.StartNew(()=> foo(arg));
Task<int> task2 = Task<int>.Factory.StartNew(()=> bar(arg));
Task<int>[] tasks = {task1, task2};
try
{
Task.WaitAll(tasks); //hits this far
if((int)task1.Result * (int)task2.Result == 99) //this seems to never get hit
{
System.Environment.Exit(0); //so this isn't called
}
else
{
System.Environment.Exit(1); // neither is this called
}
}
catch
{
.....
In the above it seems that the if
block isn't hit so neither Exit Codes are returned - the console app therefore hangs.
No exception is thrown either - I can confirm this because all the tasks are in fact completed - I just didn't include the catch
section above for brevity.
The tasks are completed quickly - they're not hanging so its not as if Task.WaitAll is still waiting - or perhaps it is, and that's something I'm missing (what is it waiting for)?
Any thoughts, advice or brutal corrections? Thanks!
Upvotes: 0
Views: 7864
Reputation: 3384
As explained by caesay above, the tasks must be hanging. To check this I would suggest giving a default time out to your WaitAll call. You can do this by passing in an int which represents the number of milliseconds that the call must wait for the tasks to be over in. Try this
Task.WaitAll(tasks, 10000); //Set to wait for 10 seconds
Then see if there is an exception or whether your "if" statement is hit. If this works then experiment with larger time intervals to see what is going on with tasks.
Also I would recommend running the code that is within foo and bar without tasks (i.e. sequentially) as a test harness to understand if there is any particular problem with these two sample methods.
Upvotes: 2
Reputation: 17213
Just for the sake of argument I did a little test (shown below) - it demonstrates one of your tasks is hanging, and not returning a value.
Task<int> task1 = Task<int>.Factory.StartNew(() =>
{
Thread.Sleep(2000);
return 10;
});
Task<int> task2 = Task<int>.Factory.StartNew(() => 15);
Task<int>[] tasks = {task1, task2};
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
Task.WaitAll(tasks);
sw.Stop();
Console.WriteLine(String.Format("tasks completed in {0}ms", sw.ElapsedMilliseconds));
}
catch
{
Console.WriteLine("Error");
}
Console.ReadLine();
If you run that, it will print tasks completed in 2000ms
(give or take a few milliseconds). All I did was copy/paste your code and add in my own tasks.
So where you say "The tasks are [...] not hanging..."
that is false - they must be hanging.
Upvotes: 4