dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.29k stars 4.74k forks source link

[Analyzer] Use the async counterpart when available #104208

Closed Bartleby2718 closed 3 months ago

Bartleby2718 commented 4 months ago

Notes:


In an async method, you can replace synchronous, void-returning methods with asynchronous, Task-returning counterparts to free up a thread.

Example (task1 and task2 are of type either Task or Task<T>)

async Task MyMethod()
{
    ...

    // before
    Task.WaitAll(task1, task2);

    // after
    await Task.WhenAll(task1, task2);

    ...
}

The caveat is that there may be false positives (if the user did want a synchronous, blocking code) and therefore this can change the semantics. However, IDE0300 also says "The code fix when this option is used might change the semantics of your code", so I think this should also be reasonable.

dotnet-policy-service[bot] commented 4 months ago

Tagging subscribers to this area: @dotnet/area-system-threading-tasks See info in area-owners.md if you want to be subscribed.

julealgon commented 4 months ago

In an async method, you can replace synchronous, void-returning methods with asynchronous, Task-returning counterparts to free up a thread.

This only applies if the underlying code supports async, otherwise all you are doing is adding extra overhead to the call.

There are also situations where the async version is not meant to be used directly:

I think creating a general-purpose analyzer for this would be either very hard, or end up leading people to the pit of failure sometimes.

The analyzer would likely have to be specific to pairs of methods where it is known to be "always the better idea" to use the "Async" version. The problem is that, depending on your application, it might just always be better to use the sync version instead to avoid the task overhead, in scenarios where you don't have much concurrent access etc.

stephentoub commented 4 months ago

If I'm understanding the suggestion, is this basically https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1849 ?

dotnet-policy-service[bot] commented 3 months ago

This issue has been marked needs-author-action and may be missing some important information.

Bartleby2718 commented 3 months ago