Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an *Awaitable* Anonymous Function as a Parameter

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 async void UpdateButton(Action<bool> post) {     if (!await post())         ErrorBox.Text = "Error posting message."; }  private void PostToTwitter() {     UpdateButton(async () => await new TwitterAction().Post("Hello, world!")); }  private void PostToFacebook() {     UpdateButton(async () => await new FacebookAction().Post("Hello, world!")); } 

Unfortunately, the !await post() doesn't work because, "Type 'void' is not awaitable." So the question is, how do I define my parameter in this method to support an awaitable parameter?

Here's how the TwitterAction().Post() is defined...

public virtual async Task<bool> Post(string messageId){...}

like image 537
jedmao Avatar asked Sep 17 '12 19:09

jedmao


People also ask

Can async function have parameters?

An async function (or AyncFunction) in the context of Async is an asynchronous function with a variable number of parameters where the final parameter is a callback.

Can you pass an async function to then?

An async function can have more than one await expression in its scope which can pause the execution inside its function scope. Once the passed Promise has been resolved, it will resume the async function's execution.

Can anonymous function async?

The main difference between an async function expression and an async function statement is the function name, which can be omitted in async function expressions to create anonymous functions.


1 Answers

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); } 
like image 54
L.B Avatar answered Sep 22 '22 20:09

L.B