ChatGPT解决这个技术问题 Extra ChatGPT

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

我有这个代码:

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”——但是在哪里呢?

@samsara:很好,我想知道他们何时最终在 C# 规范之外的某个地方记录了这一点。 IIRC,在提出这个问题时不存在任何文件。

B
BoltClock

要标记 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 收到一个错误,即不支持 Async void 方法。
@Kevin Burton:是的,异步无效通常仅限于事件处理程序。您使用的 API 不是异步的,或者具有需要异步任务 lambda 的异步版本。
任何人都可以通过提供一些链接来解释这种异步 lambda 将如何执行来帮助我吗?
@BoltClock,谢谢,但我仍然不明白未等待的异步 lambda 参数如何执行...
S
Su Llewellyn

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

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

D
Drilon Ahmetaj

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

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

return true; 代表什么?
@TheodorZoulias 对糟糕的解释感到抱歉。返回真;表示列表的每个值应该返回什么,在我的例子中,列表是 List,所以从一个列表中你正在使用 Select() 方法创建另一个列表。为了简单起见,我删除了我的逻辑。这里重要的部分是我需要在 lambda 表达式中调用一个可等待的方法,这是通过放置 async 关键字来完成的。
Drilon 如果 listList<bool>,则 xbool。这很清楚。 return true; 不清楚。为什么要返回一个常量值而不是 await SomeMethod(x) 的结果,或者至少是 x 本身?这个返回值在哪里使用?您的示例没有将 list.Select 的结果分配给任何东西。抱歉,但目前我不得不对答案投反对票。如果需要,您可以尝试通过编辑来改进它。
您不必为自己的身份感到抱歉...返回取决于可等待的方法。例子。如果 SomeMethod 返回 not null ,则返回 true,否则返回 false,这将对每个值进行映射。但我不想提供所有代码,因为它与 async 关键字问题无关。