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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With