Besserer Weg, um Fehlermeldungen in asynchronen Methoden anzuzeigen
Die Tatsache, dass wir das nicht nutzen könnenawait
Stichwort incatch
Blöcke macht es ziemlich umständlich, Fehlermeldungen von asynchronen Methoden in WinRT anzuzeigen, da dieMessageDialog
API ist asynchron. Idealerweise würde ich gerne folgendes schreiben können:
private async Task DoSomethingAsync()
{
try
{
// Some code that can throw an exception
...
}
catch (Exception ex)
{
var dialog = new MessageDialog("Something went wrong!");
await dialog.ShowAsync();
}
}
Aber stattdessen muss ich es so schreiben:
private async Task DoSomethingAsync()
{
bool error = false;
try
{
// Some code that can throw an exception
...
}
catch (Exception ex)
{
error = true;
}
if (error)
{
var dialog = new MessageDialog("Something went wrong!");
await dialog.ShowAsync();
}
}
Alle Methoden, die dies tun müssen, müssen einem ähnlichen Muster folgen, was mir wirklich nicht gefällt, da es die Lesbarkeit des Codes verringert.
Gibt es eine bessere Möglichkeit, damit umzugehen?
BEARBEITEN: Ich habe mir folgendes ausgedacht (ähnlich wie es Svick in seinen Kommentaren vorgeschlagen hat):
static class Async
{
public static async Task Try(Func<Task> asyncAction)
{
await asyncAction();
}
public static async Task Catch<TException>(this Task task, Func<TException, Task> handleExceptionAsync, bool rethrow = false)
where TException : Exception
{
TException exception = null;
try
{
await task;
}
catch (TException ex)
{
exception = ex;
}
if (exception != null)
{
await handleExceptionAsync(exception);
if (rethrow)
ExceptionDispatchInfo.Capture(exception).Throw();
}
}
}
Verwendungszweck:
private async Task DoSomethingAsync()
{
await Async.Try(async () =>
{
// Some code that can throw an exception
...
})
.Catch<Exception>(async ex =>
{
var dialog = new MessageDialog("Something went wrong!");
await dialog.ShowAsync();
});
}
.Catch<...>
Anrufe können verkettet werden, um mehrere zu imitierencatch
Blöcke.
Aber ich bin mit dieser Lösung nicht wirklich zufrieden. Die Syntax ist noch umständlicher als zuvor ...