我有以下同步代码,运行良好:
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);
}
}
我想将其更改为异步。因此:
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);
}
它编译。但我使用的一个分析器(Meziantou.Analyzer(现在表明;更喜欢使用"wait using";。我从未使用过wait-using(尽管我过去尝试过几次,但总是遇到与现在相同的问题(。但我想使用它,所以:
await using StreamWriter writer = new StreamWriter(OutputDirectory + @"export.txt").ConfigureAwait(false);
现在它不再编译: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);
这使它通过了CS0029,但现在后面的代码没有编译:Error CS1061 'ConfiguredAsyncDisposable' does not contain a definition for 'WriteLineAsync'
(以及FlushAsync
的类似代码。Soooo…也许是强制转换?
await ((StreamWriter)writer).WriteLineAsync(title).ConfigureAwait(false);
编号:Error CS0030 Cannot convert type 'System.Runtime.CompilerServices.ConfiguredAsyncDisposable' to 'System.IO.StreamWriter'
我现在和过去都在谷歌上搜索过一堆,读过几次,但我一直完全不知道如何使用这个"等待使用";事情我该怎么做?谢谢
当前的await using
语法(C#10(在支持配置IAsyncDisposable
s的等待方面还有很多不足之处。我们能做的最好的事情是:
private async Task GenerateExportOutputAsync()
{
StreamWriter writer = new(Coordinator.OutputDirectory + @"export.txt");
await using (writer.ConfigureAwait(false))
{
//...
}
}
这并不比根本不使用await using
语法紧凑得多:
private async Task GenerateExportOutputAsync()
{
StreamWriter writer = new(Coordinator.OutputDirectory + @"export.txt");
try
{
//...
}
finally { await writer.DisposeAsync().ConfigureAwait(false); }
}
GitHub相关问题:在";等待使用";公告
它可以在两行中完成:
private async Task GenerateExportOutputAsync()
{
StreamWriter writer = new(Coordinator.OutputDirectory + @"export.txt");
await using var _ = writer.ConfigureAwait(false);
//...
}