green-code-initiative / ecoCode

Reduce the environmental footprint of your software programs with SonarQube
https://ecocode.io
GNU General Public License v3.0
139 stars 76 forks source link

[EC93] [C#] Return Task directly #339

Closed Djoums closed 3 months ago

Djoums commented 3 months ago

Why is this an issue ?

Asynchronous methods that contain a single awaited statement can be optimized by removing the async modifier and returning the awaited Task directly. Doing so reduces the overhead of the state machine generated for the asynchronous method, leading to more efficient code and improving the resource efficiency of the application.

When can it be ignored ?

When this rule is applied, exception handling is deferred to the main caller instead, which may or may not be desirable. The decision should be done with consideration to the context in which the method is used.

Non-compliant examples

public static async Task Test1()
{
    await Task.Delay(1000); // Non-compliant, return the Task directly.
}

public static async Task Test2()
{
    await MyAsyncMethod(); // Non-compliant, exceptions within MyAsyncMethod are handled by the method itself.
}

Compliant examples

public static Task Test1()
{
    return Task.Delay(1000); // Compliant
}

public static Task Test2()
{
    return MyAsyncMethod(); // Compliant, exceptions within MyAsyncMethod are handled by the caller of Test2.
}