Home > Software design >  c# blazor avoid using 'async' lambda when delegate type returns 'void'
c# blazor avoid using 'async' lambda when delegate type returns 'void'

Time:12-10

I get the following warning in JetBrains Rider and I can't find a way to workaround it. It's a blazor WASM project with .net 6.

Avoid using 'async' lambda when delegate type returns 'void'

Sample code Razor:

<Validation Validator="async e => await ValidateFieldAsync(e)">

Sample code c#:

protected async Task ValidateFieldAsync(ValidatorEventArgs args)
{
    // Some code with awaits etc.
}

Jetbrains describes this warning here:

https://www.jetbrains.com/help/resharper/AsyncVoidLambda.html

But what is the best practice here to fix this?

Thanks for any hints!

CodePudding user response:

You do not need a lambda here at all.

<Validation Validator="ValidateFieldAsync" >

or

<Validation Validator=@ValidateFieldAsync >

or

<Validation Validator=ValidateFieldAsync >

Should all work - it is just a matter of your preference for style.

You are correct to return a Task from this method.

CodePudding user response:

It looks like Resharper lost track here. The warning is incorrect.

But you can improve this anyway,

<Validation Validator="e => ValidateFieldAsync(e)">

As long as ValidateFieldAsync() still returns async Task this is still async and awaitable, just with a little less overhead. The aync and await in the lambda were adding an extra layer that isn't needed. And it might just stop that false warning, I can't check now.

When you don't need any argument or when Blazor can auto add it then you can follow @MisterMagoo's answer.

CodePudding user response:

When calling functions from razor don't call Task functions. Call void functions because that is what is expected.

<Validation Validator="e => ValidateFieldAsync(e)">

Then the actual code:

protected async void ValidateFieldAsync(ValidatorEventArgs args)
{
    // Some code with awaits etc.
}

It will still run async so don't worry about having async in the razor calling code.

  • Related