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


215

我有以下代码:

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'运算符应用于调用结果 ”(与评论)。

因此,我给它添加了一个“等待”,但是,当然,我也需要在某个地方添加一个“异步”-但是在哪里?



1
@samsara:很好,我想知道他们何时最终在C#规范之外的地方对此进行了记录。IIRC,在提出此问题时尚无文档。
BoltClock

Answers:


365

要标记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);
}));

我从Visual Studio得到一个错误,该错误不支持异步void方法。
凯文·伯顿

@Kevin Burton:是的,异步void通常只限于事件处理程序。您使用的API不是异步的,或者是具有异步版本的API,而该异步版本需要异步Task Lambda。
BoltClock

22

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

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.