在'等待'运算符只能异步拉姆达前pression内使用 [英] The 'await' operator can only be used within an async lambda expression

查看:149
本文介绍了在'等待'运算符只能异步拉姆达前pression内使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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:

在'等待'运算符只能异步拉姆达前pression内使用。考虑标志着这个拉姆达前pression与异步修改

该方法被标记等待。如果我删除等待从showSaveDialog之前,它编译(和作品),但我得到的,我真的应该使用的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

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

How do I use await in this context?

推荐答案

您必须标记你的lambda前pression为异步,就像这样:

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

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

这篇关于在'等待'运算符只能异步拉姆达前pression内使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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