如何标记异步lambda表达式?

3

我这里有一段代码,想知道在哪里加上 await 关键字。我尝试过使用 lambda => 和普通方法,但都没有成功。

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

    var contextMenu = new PopupMenu();

    contextMenu.Commands.Add(new UICommand("Edit this Group", (contextMenuCmd) =>
    {
        Frame.Navigate(typeof(LocationGroupCreator), nameOfGroup );
    }));

    contextMenu.Commands.Add(new UICommand("Delete this Group", (contextMenuCmd) =>
    {
        SQLiteUtils rfd = new SQLiteUtils();
        rfd.DeleteGroupAsync(nameOfGroup ); 
    }));

    await contextMenu.ShowAsync(args.GetPosition(this));
}

我添加了一个await,但我需要在某个地方添加async ... 但是应该在哪里添加呢?
Resharper的检查提示:"因为此调用未被等待,所以在完成调用之前,当前方法的执行将继续进行。考虑将'await'运算符应用于调用的结果"
非常感谢您的帮助!

可能是无法等待异步lambda的重复问题。 - trailmax
2
可能是在哪里标记lambda表达式为async?的重复问题。 - Kirk Larkin
1
Stephen Cleary写了一个关于委托类型及其await对应的精彩列表。https://blog.stephencleary.com/2014/02/synchronous-and-asynchronous-delegate.html - ChristianMurschall
3个回答

8
只需在参数列表前添加async即可。
// Command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
    SQLiteUtils rfd = new SQLiteUtils();
    await rfd.DeleteGroupAsync(groupName);
}));

1
谢谢。这样就解决了。我只是在最后一行添加了async。请编辑。 - Irelia
2
让我们祈祷UICommand期望一个异步委托。否则,它可能会造成严重破坏。 - ChristianMurschall

3
为了标记lambda异步,请使用以下语法:
async (contextMenuCmd) =>
{
   SQLiteUtils rfd = new SQLiteUtils();
   await rfd.DeleteGroupAsync(nameOfGroup ); 
}

3
只需将其添加在括号前面,像这样:

contextMenu.Commands.Add(new UICommand("Edit this Group", async (contextMenuCmd) =>
{

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接