Coder Perfect

I’m not sure how to make a lambda expression async.

Problem

I’ve got this code:

private async void ContextMenuForGroupRightTapped(object sender, RightTappedRoutedEventArgs args)
{
    CheckBox ckbx = null;
    if (sender is CheckBox)
    {
        ckbx = sender as CheckBox;
    }
    if (null == ckbx)
    {
        return;
    }
    string groupName = ckbx.Content.ToString();

    var contextMenu = new PopupMenu();

    // Add a command to edit the current Group
    contextMenu.Commands.Add(new UICommand("Edit this Group", (contextMenuCmd) =>
    {
        Frame.Navigate(typeof(LocationGroupCreator), groupName);
    }));

    // Add a command to delete the current Group
    contextMenu.Commands.Add(new UICommand("Delete this Group", (contextMenuCmd) =>
    {
        SQLiteUtils slu = new SQLiteUtils();
        slu.DeleteGroupAsync(groupName); // this line raises Resharper's hackles, but appending await raises err msg. Where should the "async" be?
    }));

    // Show the context menu at the position the image was right-clicked
    await contextMenu.ShowAsync(args.GetPosition(this));
}

…that Resharper’s inspection found to be unsatisfactory, “Because this call isn’t awaited, the present method’s execution proceeds before the call is finished. Consider using the ‘await’ operator on the call’s result ” (on the line with the comment).

As a result, I added a “await” to it, but I still need to put a “async” someplace – but where?

Asked by B. Clay Shannon-B. Crow Raven

Solution #1

Simply add async before the argument list of a lambda to make it async:

// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
    SQLiteUtils slu = new SQLiteUtils();
    await slu.DeleteGroupAsync(groupName);
}));

Answered by BoltClock

Solution #2

And for those of you who use an anonymous expression, here’s some advice:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

Answered by Su Llewellyn

Solution #3

Apply the async keyword directly before the parameter if you’re inside a LINQ method syntax:

 list.Select(async x =>
            {
                await SomeMethod(x);
                return true;
            });

Answered by Drilon Ahmetaj

Post is based on https://stackoverflow.com/questions/14015319/where-do-i-mark-a-lambda-expression-async