c# - 将 await 与 MessageDialog.ShowAsync() 一起使用时出错

标签 c# asynchronous uwp

在一个方法中我有一个 try catch像这样阻止:

try
{
    // do something
}
catch (Exception ex)
{
    MessageDialog message = new MessageDialog(ex.ToString());
    message.ShowAsync();
}

我收到以下关于 message.ShowAsync() 行的警告:

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

说完了:

try
{
    // do something
}
catch (Exception ex)
{
    MessageDialog message = new MessageDialog(ex.ToString());
    await message.ShowAsync();
}

现在我得到一个异常(exception):

The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

我什至尝试这样做以避免在 catch block 内等待:

Exception exception;
try
{
    // do something
}
catch (Exception ex)
{
    exception = ex;
}

if (exception != null)
{
    MessageDialog message = new MessageDialog(ex.ToString());
    message.ShowAsync();
}

然而,这并没有改变任何东西。

我必须做什么才能使用 await在这种情况下? MessageDialog.ShowAsync()就 IntelliSense 显示返回 Windows.Foundation.IAsyncOperation<IUICommand> 的可等待方法而言.

最佳答案

您的函数必须是“异步的”才能使用异步运算符:

例如:

 private async void Test()
 {
    MessageDialog message = new MessageDialog(ex.ToString());
    await message.ShowAsync();
 }

关于c# - 将 await 与 MessageDialog.ShowAsync() 一起使用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38050955/

相关文章:

javascript - 在 React.js 中将 Async/Await 与 Axios 一起使用

mvvm - UWP - 使用 x 时如何指定更新顺序 :Bind?

c# - 我需要做一个直方图拉伸(stretch)

c# - MVC View 中的 Html 元素为空

javascript - 单击按钮时调用 MVC Controller 和操作方法

c# - 无法发布 Azure 函数

c# - 如何访问 AppData 文件夹

javascript - 异步调用内的同步调用

c# - 如何调试 UWP xaml 绑定(bind)?

c# - UWP 错误?绑定(bind)到某些嵌套的 DependencyProperty 将不起作用