semihokur / AsyncFixer

Advanced async/await Diagnostics and CodeFixes for C#
Apache License 2.0
165 stars 11 forks source link

What's the preferred way to fix AsyncFixer02 warning when accessing task.Result after Task.WhenAll(tasks)? #35

Open 0liver opened 1 year ago

0liver commented 1 year ago

We have several occurrences of the following pattern:

Task[] tasks = CreateTasks();

await Task.WhenAll(tasks);

foreach(var task in tasks)
    Console.WriteLine(task.Result);

The above code will generate an AsyncFixer02 warning for task.Result. This seems to be not necessary, because the task will already be completed at this point.

What is the expected fix to this? I'm tired of suppressing the warning for every such place in our code.

Piedone commented 1 year ago

I can't really answer the question, but this may be equivalent for your code base and doesn't cause a warning:

Task[] tasks = CreateTasks();

await Task.WhenAny(tasks);

foreach (var task in tasks)
    Console.WriteLine(await task);

This has the added benefit that if you do something with the results that takes non-trivial time in the foreach then in the worst case this will take as much time as the WhenAll() code, but can be quicker if the slowest task is not the first one.

0liver commented 1 year ago

Good to see you, @Piedone! Thanks for the suggestion - nice hack. Actually, using await task instead of task.Result will work just as well when using Task.WhenAll() - which is more expressive and less surprising, I guess. But the idea is interesting!