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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14015319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:24:22  来源:igfitidea点击:

Where do I mark a lambda expression async?

c#lambdaresharperwindows-store-appsasync-await

提问by B. Clay Shannon

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 complained about with, "Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call" (on the line with the comment).

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

And so, I prepended an "await" to it but, of course, I then need to add an "async" somewhere, too - but where?

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

采纳答案by BoltClock

To mark a lambda async, simply prepend asyncbefore its argument list:

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

回答by Su Llewellyn

And for those of you using an anonymous expression:

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

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