Passing an *Awaitable* Anonymous Function as a Parameter

后端 未结 2 1336
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 16:56
    private async void UpdateButton(Func<Task<bool>> post)
    {
        if (!await post())
            ErrorBox.Text = "Error posting message.";
    }
    

    --EDIT--

    UpdateButton(()=>Post("ss"));
    
    private async void UpdateButton(Func<Task<bool>> post)
    {
        if (!await post())
            this.Text = "Error posting message.";
    }
    
    public virtual async Task<bool> Post(string messageId)
    {
        return await Task.Factory.StartNew(() => true);
    }
    
    0 讨论(0)
  • 2021-01-07 17:03

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

    This provides something that's "awaitable".

    I believe this will work, given your current code:

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

    If you do not want to start the Task<bool> 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<Task<bool>> post)
    {
        if (!await post())
            ErrorBox.Text = "Error posting message.";
    }
    
    // This will work if Post returns Task<bool> in the current API...
    private void PostToTwitter()
    {
        UpdateButtonAsync(() => new TwitterAction().Post("Hello, world!"));
    }
    

    This causes the lambda to return the Task<bool> (no async/await required, as Post already returns Task<bool>), 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<T>, you can just pass that around and await it directly.

    0 讨论(0)
提交回复
热议问题