繁体   English   中英

我在哪里标记 lambda 表达式异步?

[英]Where do I mark a lambda expression async?

我有这个代码:

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

... Resharper 的检查抱怨说,“因为没有等待这个调用,所以在调用完成之前继续执行当前方法。考虑将 'await' 运算符应用于调用的结果”(在带有评论)。

所以,我在前面加上了一个“await”,但是,当然,我还需要在某处添加一个“async”——但是在哪里呢?

要标记lambda异步,只需在其参数列表之前添加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);
}));

对于那些使用匿名表达式的人:

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

如果您在 LINQ 方法语法中,请在参数前应用 async 关键字:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM