“await"运算符只能在异步 lambda 表达式中使用 [英] The 'await' operator can only be used within an async lambda expression

查看:83
本文介绍了“await"运算符只能在异步 lambda 表达式中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 c# Windows 应用商店应用.当单击另一个 MessageDialog 中的一个命令按钮时,我试图启动一个 MessageDialog.这样做的目的是警告用户他们的内容未保存,如果他们单击取消,则会提示他们使用单独的保存对话框进行保存.

I've got a c# Windows Store app. I'm trying to launch a MessageDialog when one of the command buttons inside another MessageDialog is clicked. The point of this is to warn the user that their content is unsaved, and if they click cancel, it will prompt them to save using a separate save dialog.

这是我的showCloseDialog"函数:

Here's my "showCloseDialog" function:

private async Task showCloseDialog()
{
    if (b_editedSinceSave)
    {
        var messageDialog = new MessageDialog("Unsaved work detected. Close anyway?", "Confirmation Message");

        messageDialog.Commands.Add(new UICommand("Yes", (command) =>
        {
            // close document
            editor.Document.SetText(TextSetOptions.None, "");
        }));

        messageDialog.Commands.Add(new UICommand("No", (command) =>
        {
            // save document
            await showSaveDialog();
        }));

        messageDialog.DefaultCommandIndex = 1;
        await messageDialog.ShowAsync();
    }
}

在 VS 中我得到一个编译器错误:

In VS I get a compiler error:

await"运算符只能在异步 lambda 表达式中使用.考虑使用 'async' 修饰符来标记这个 lambda 表达式`

The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier`

该方法用await 标记.如果我从 showSaveDialog 之前删除 await,它会编译(并工作),但我收到一个警告,我真的应该使用 await

The method is marked with await. If I remove await from before showSaveDialog, it compiles (and works) but I get a warning that I really should use await

在这种情况下我如何使用 await?

How do I use await in this context?

推荐答案

您必须将 lambda 表达式标记为 async,如下所示:

You must mark your lambda expression as async, like so:

messageDialog.Commands.Add(new UICommand("No", async (command) =>
{
    await showSaveDialog();
}));

这篇关于“await"运算符只能在异步 lambda 表达式中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆