The 'await' operator can only be used within an async lambda expression

C#LambdaModal DialogWindows Store-AppsAsync Await

C# Problem Overview


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.

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

In VS I get a compiler error:

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

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?

C# Solutions


Solution 1 - C#

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

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

Solution 2 - C#

In my case I needed to call an asynchronous method inside a async foreach. The solution was something like this:

await list.ForEachAsync(async item =>
{
	IEnumerable<Object> data = await _repository.Get();
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionroryokView Question on Stackoverflow
Solution 1 - C#Boris ParfenenkovView Answer on Stackoverflow
Solution 2 - C#Jhonnatan EduardoView Answer on Stackoverflow