Passing an *Awaitable* Anonymous Function as a Parameter

后端 未结 2 1335
Happy的楠姐
Happy的楠姐 2021-01-07 16:30

Code first. This is what I\'m trying to do. I\'m close, but I think I just need to fix the way I\'ve defined my parameter in the UpdateButton method.

private         


        
2条回答
  •  执笔经年
    2021-01-07 17:03

    You need to pass this as a Task, not an Action.

    This provides something that's "awaitable".

    I believe this will work, given your current code:

    private async Task UpdateButtonAsync(Task post)
    {
        if (!await post)
            ErrorBox.Text = "Error posting message.";
    }
    
    // This will work if Post returns Task in the current API...
    private void PostToTwitter()
    {
        UpdateButtonAsync(new TwitterAction().Post("Hello, world!"));
    }
    

    If you do not want to start the Task immediately, and need to keep it as passing a lambda, there is still no reason for the lambda to be async. In that case, you could use:

    private async Task UpdateButtonAsync(Func> post)
    {
        if (!await post())
            ErrorBox.Text = "Error posting message.";
    }
    
    // This will work if Post returns Task in the current API...
    private void PostToTwitter()
    {
        UpdateButtonAsync(() => new TwitterAction().Post("Hello, world!"));
    }
    

    This causes the lambda to return the Task (no async/await required, as Post already returns Task), and the update method to run the lambda.

    Personally, I find the first option (above) simpler, and suspect it is more likely what you want. Given your API already returns Task, you can just pass that around and await it directly.

提交回复
热议问题