Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 729
roryok Avatar asked Dec 15 '13 10:12

roryok


People also ask

What happens if async method is called without await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

How do you create async in lambda expression?

Open the Functions page of the Lambda console. Choose a function. Under Function overview, choose Add destination. For Source, choose Asynchronous invocation.


1 Answers

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

messageDialog.Commands.Add(new UICommand("No", async (command) => {     await showSaveDialog(); })); 
like image 113
Boris Parfenenkov Avatar answered Oct 17 '22 03:10

Boris Parfenenkov