[C#] await inside loop should be a code smell

I would like to suggest a new code smell: the await inside a regular loop.

I believe that this could be refactor in several ways, both maintaining the (possibly) desired “relief of load” on the other end AND allowing parallel execution

A non compliant code would be:

foreach(var uri in listOfUri)
    await DoSomething(uri);

a possible refactor would be:

List<Task> tasks = new List<Task>();
foreach(var uri in listOfUri)
    tasks.Add(DoSomething(uri));
await Task.WhenAll(tasks);

There are other refactors that would allow sequential download (via recursion for example) and batching can be achieved using Parallel.Foreach and other means.

Refer to New Code Smell Suggestion: await inside loops for more details

thanks @Leonardo-Ferreira , we’re going to discuss it internally

HI there! any news? I kinda lost track of this

I would argue that it might (in some cases) be a code smell. However, only if each iteration of the loop is independent from the other. That is (far from) trivial to detect. As a result, this rule potentially reports a lot false positives.

Hi @Leonardo-Ferreira !

I tend to agree with @Corniel , it could be hard to distinguish between those 2 cases. Since this rule could lead to a number of FP cases, it won’t be a Sonar Way rule and we have no plans on working on it for now.

You can write your own Roslyn analyzer rule, add it to your projects and the results will be automatically imported in SonarQube by the Scanner for .NET as external issues.