semihokur / AsyncFixer

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

UnnecessaryAsync analyzer becomes smarter with dataflow analysis #9

Closed semihokur closed 3 years ago

semihokur commented 3 years ago

Implemented a depth-limited dataflow analysis to get the list of the variable names accessed in the await statement. This is needed to understand whether there are any variables created via using statement are accessed in the await statement. If there is one, we cannot remove async&await keywords as it can cause ObjectDisposedException.

In the example below, AsyncFixer can see that the last await statement involves the disposable object, stream created via using statement.

async Task foo()
{
    using var stream = new MemoryStream();
    int streamOperation()
    {
        return stream.Read(null);
    }

    Task t = Task.Run(() => streamOperation());
    await t;
}

However, in the example below, it is perfectly safe to remove async&await keywords:

async Task foo()
{
    using var stream = new MemoryStream();
    stream.Read(null);
    await Task.Delay(1000);
}