Tengo el siguiente código síncrono, que funciona bien:
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); } }Quiero cambiarlo para que sea asíncrono. Entonces:
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); }que compila. Pero uno de los analizadores que uso ( Meziantou.Analyzer ) ahora sugiere que "prefiero usar 'esperar usando'". Nunca he usado await using (aunque lo he intentado varias veces en el pasado y siempre me he encontrado con los mismos problemas que tengo ahora). Pero me gustaría usarlo, así que:
await using StreamWriter writer = new StreamWriter(OutputDirectory + @"\export.txt").ConfigureAwait(false); Ahora ya no compila: CS0029 Cannot implicitly convert type 'System.Runtime.CompilerServices.ConfiguredAsyncDisposable' to 'System.IO.StreamWriter' . OK, bien, así que lo cambio para usar var en su lugar:
await using var writer = new StreamWriter(OutputDirectory + @"\export.txt").ConfigureAwait(false); Lo que supera el CS0029, pero ahora el código posterior no se compila: Error CS1061 'ConfiguredAsyncDisposable' does not contain a definition for 'WriteLineAsync' (y una similar para FlushAsync . Así que... ¿tal vez lanzarlo?
await ((StreamWriter)writer).WriteLineAsync(title).ConfigureAwait(false); No: Error CS0030 Cannot convert type 'System.Runtime.CompilerServices.ConfiguredAsyncDisposable' to 'System.IO.StreamWriter'
Busqué en Google un montón y leí un montón, tanto ahora como varias veces en el pasado, pero no he podido descubrir cómo usar esta cosa de "esperar usando". ¿Como lo puedo hacer? Gracias.
La sintaxis await using actualmente ( C# 10 ) deja mucho que desear, con respecto a su soporte para configurar la espera de IAsyncDisposable s. Lo mejor que podemos hacer es esto:
private async Task GenerateExportOutputAsync() { StreamWriter writer = new(Coordinator.OutputDirectory + @"\export.txt"); await using (writer.ConfigureAwait(false)) { //... } } ... que en realidad no es mucho más compacto que no usar la sintaxis await using en absoluto:
private async Task GenerateExportOutputAsync() { StreamWriter writer = new(Coordinator.OutputDirectory + @"\export.txt"); try { //... } finally { await writer.DisposeAsync().ConfigureAwait(false); } }Problema de GitHub relacionado: uso de ConfigureAwait en la declaración "await using" .