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
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);
}
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.