gpt4 book ai didi

c# - 在异步方法中显示错误消息的更好方法

转载 作者:可可西里 更新时间:2023-11-01 08:29:34 25 4
gpt4 key购买 nike

事实上我们不能使用 await catch 中的关键字 block 使得在 WinRT 中显示来自异步方法的错误消息非常尴尬,因为 MessageDialog API 是异步的。理想情况下,我希望能够这样写:

    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();
}
}

但是我必须这样写:

    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();
}
}

所有需要这样做的方法都必须遵循类似的模式,我真的不喜欢这种模式,因为它降低了代码的可读性。

有没有更好的方法来处理这个问题?


编辑:我想出了这个(这与 svick 在他的评论中建议的类似):

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();
}
}
}

用法:

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<...>可以链接调用以模仿多个 catch block 。

但我对这个解决方案不是很满意;语法比以前更笨拙了...

最佳答案

您已经在 TPL 中拥有该功能

        await Task.Run(async () =>
{
// Some code that can throw an exception
...
}).ContinueWith(async (a) =>
{
if (a.IsFaulted)
{
var dialog = new MessageDialog("Something went wrong!\nError: "
+ a.Exception.Message);
await dialog.ShowAsync();
}
else
{
var dialog2 = new MessageDialog("Everything is OK: " + a.Result);
await dialog2.ShowAsync();
}
}).Unwrap();

我在这台机器上没有安装 Windows 8,所以我在 Windows 7 中进行了测试,但我认为是一样的。*编辑如评论中所述,它需要 .Unwrap();最后等待工作

关于c# - 在异步方法中显示错误消息的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18310236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com