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!
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.
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.