CA2012 warning on using ValueTask in Blazor. How to implement "fire and forget" correctly in Blazor?

Viewed 469

IJSRuntime.InvokeVoidAsync() called as last thing in a code path causes CA2012 (Use ValueTasks correctly) warning. Can it be safely ignored, or should I fix that with awaiting it?

When I add .Preserve() at the end of my synchronous call the warning disappears, the code works the same. Why is that? What happens? What does this method do? The documentation (of Preserve() method) is unclear.

I want "fire and forget" use of a method that returns a ValueTask. What is the most correct way to achieve that, calling it from a synchronous method?

To add some context - I execute JS from my Blazor code. I do not rely on effects caused by the JS code after calling it. That's why I do not await it. I can refactor my code to await the ValueTask but would it serve any other purpose than making the Code Analyzer happy?

1 Answers

But what about calling from old school event handlers? They can be at best async void

Blazor eventhandlers went back to school and can all be async Task. The Razor engine knows how to deal with that.

The only problem is with non-Blazor events, like the Elapsed event from a Timer. You may need async void there.

For now my idea is to try to go "async all the way"

Yes, that is the way to go.

Going sync (non async) is a small optimization for code-paths that don't need anything async. For example the IncrementCount() method (eventhandler) in the Counter example.

but would it serve any other purpose than making the Code Analyzer happy?

It would help Blazor to refresh the UI after your update is complete. A fire-and-forget has to do its own StateHasChanged() logic for one.

If you really want to f&f, _ = DoSomethingAsyncWithoutAwait();

InvokeAsync() sends your Task to the main UI thread. Currently that only applies to Blazor Server. It is only required when the Task needs to update the UI and from normal Blazor code it is then better to just await. The normal Blazor lifecycle will not be blocked. Using it to avoid a warning is sub-optimal.

Related