如何使“await using”语法正确?

Bob*_*man 10 .net c# asynchronous async-await iasyncdisposable

我有以下同步代码,运行良好:

    private void GenerateExportOutput()
    {
        using StreamWriter writer = new(Coordinator.OutputDirectory + @"\export.txt");

        if (this.WikiPagesToExport.IsEmpty)
        {
            return;
        }

        var wanted = new SortedDictionary<string, WikiPage>(this.WikiPagesToExport, StringComparer.Ordinal);
        foreach (var title in wanted.Keys)
        {
            writer.WriteLine(title);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想将其更改为异步。所以:

    private async Task GenerateExportOutputAsync()
    {
        using StreamWriter writer = new(Coordinator.OutputDirectory + @"\export.txt");

        if (this.WikiPagesToExport.IsEmpty)
        {
            return;
        }

        var wanted = new SortedDictionary<string, WikiPage>(this.WikiPagesToExport, StringComparer.Ordinal);
        foreach (var title in wanted.Keys)
        {
            await writer.WriteLineAsync(title).ConfigureAwait(false);
        }

        await writer.FlushAsync().ConfigureAwait(false);
    }
Run Code Online (Sandbox Code Playgroud)

哪个编译。但我使用的分析器之一(Meziantou.Analyzer)现在建议我“更喜欢使用‘await using’”。我从来没有使用过await using(尽管我过去尝试过几次并且总是遇到现在遇到的相同问题)。但我想使用它,所以:

        await using StreamWriter writer = new StreamWriter(OutputDirectory + @"\export.txt").ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

现在它不再编译:CS0029 Cannot implicitly convert type 'System.Runtime.CompilerServices.ConfiguredAsyncDisposable' to 'System.IO.StreamWriter'. 好的,好吧,所以我将其更改为使用var

        await using var writer = new StreamWriter(OutputDirectory + @"\export.txt").ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

这让它通过了 CS0029,但现在后面的代码无法编译:(Error CS1061 'ConfiguredAsyncDisposable' does not contain a definition for 'WriteLineAsync'以及类似的FlushAsync.Soooo...也许可以转换它?

            await ((StreamWriter)writer).WriteLineAsync(title).ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

没有:Error CS0030 Cannot convert type 'System.Runtime.CompilerServices.ConfiguredAsyncDisposable' to 'System.IO.StreamWriter'

我现在和过去几次都在谷歌上搜索了一堆并阅读了一堆,但我完全无法弄清楚如何使用这个“等待使用”的东西。我怎样才能这样做呢?谢谢。

The*_*ias 18

目前的语法await using( C# 10 ) 在支持配置等待IAsyncDisposables 方面还有很多不足之处。我们能做的最好的就是:

private async Task GenerateExportOutputAsync()
{
    StreamWriter writer = new(Coordinator.OutputDirectory + @"\export.txt");
    await using (writer.ConfigureAwait(false))
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

await using...这并不比根本不使用语法更紧凑:

private async Task GenerateExportOutputAsync()
{
    StreamWriter writer = new(Coordinator.OutputDirectory + @"\export.txt");
    try
    {
        //...
    }
    finally { await writer.DisposeAsync().ConfigureAwait(false); }
}
Run Code Online (Sandbox Code Playgroud)

相关 GitHub 问题:在“await using”声明中使用ConfigureAwait