Many SO answers use await Task.Delay(1)
to solve various async rendering issues in Blazor (wasm). I've even found a number of places in my own code where doing that "makes it work".
However it's always stated as matter of fact, without a thorough explanation, and I can't find this technique in the docs either.
Some questions:
await Task.Delay(1)
- when would I use this technique, what is the use case?Task.Delay(1)
and Task.Yield()
?
- Why use await Task.Delay(1)
To show intermediate results in an eventhandler. The canonical code for a screen update is
StateHasChanged(); // request a render
await Task.Delay(1); // allow the render to execute
- The docs do not discuss this
It is usually not needed. But there's no argument against using it either. I figured out how to use it when solving a problem like this. And I got some negative feedback, see the comments under those posts.
- Any difference between Task.Delay(1) and Task.Yield()?
Yes, Task.Yield() looks more sensible but I found it does not always work. See Stephen Cleary's answer here.