Search code examples
c#asp.net-coreasync-awaitblazorblazor-webassembly

Why use await Task.Delay(1) in Blazor wasm?


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:

  • Why use await Task.Delay(1) - when would I use this technique, what is the use case?
  • The docs do not discuss this (that I could find); is it because it's a hack, or is it a legitimate way to deal with the use case?
  • Any difference between Task.Delay(1) and Task.Yield()?

Solution

    • Why use await Task.Delay(1)

    To show intermediate results in an eventhandler.

    • 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.