Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
0liver opened this issue Sep 13, 2023 · 2 comments

Comments

@0liver
Copy link

0liver commented Sep 13, 2023

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
Copy link

Piedone commented Sep 28, 2023

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
Copy link
Author

0liver commented Sep 29, 2023

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants