Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Func<T, Task> and anonymous async await Action<T>

I am developing on ASP.NET Core Blazor and sometimes I look on GitHub to learn something. This question isn't strictly related to Blazor, but I saw a lot of Blazor developers doing what I am going to explain.

I noticed that some components accept an Action<T> as a parameter and others accept a Func<T, Task>.

/* example */

public class MyComponentA : ComponentBase 
{
    [Parameter] public Action<T> OnClick {get; set;}

    //... other methods
}

public class MyComponentB : ComponentBase 
{
    [Parameter] public Func<T, Task> OnClickAsync {get; set;}

    //... other methods
}

What I understood is that you should bind Action<T> to a no-async/await method and Func<T, Task> to an async/method. So far so good.

However, I see that someone is used to pass an async/await anonymous function as Action<T>, like OnClick=@(async (item) => await Foo(item)). Sometimes, I have passed an anonymous async/await function as Action too, and it works.

  • Is it correct?

  • Is there any kind of side effect?

  • Is an Action<T> that invokes an anonymous async/await function, an asynchronous call?

like image 766
Leonardo Lurci Avatar asked Dec 05 '22 08:12

Leonardo Lurci


1 Answers

Action<T> does not allow a return value, and only methods that return an awaitable type (usually Task or Task<T>) can be awaited.

Therefore, if you use pass an asynchronous method as Action<T> it will always be fire and forget.

Using Func with Task as a return value may be awaited, depending on how the method is implemented.

like image 119
Johnathan Barclay Avatar answered Jan 05 '23 00:01

Johnathan Barclay