sukesh
sukesh

Reputation: 2423

Blazor - When to use Async life cycle methods

Is there any thumbrule for a beginner to understand when to use which life cycle methods, when developing a Blazor Server app.

OnInitialized() vs OnInitializedAsync()
OnParametersSet() vs OnParametersSetAsync()
OnAfterRender() vs OnAfterRenderAsync()

Upvotes: 1

Views: 836

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273244

OnInitialized() vs OnInitializedAsync()

Prefer the simple OnInitialized() to set data without async, like message="hello";.
As soon as you have to call and await async methods, for instance on HttpClient, switch to OnInitializedAsync().

More rules of thumb:

  • do not use .Result or .Wait() on async methods
  • do not start async methods without awaiting them
  • do not use async void except in very rare cases.

When you get it wrong there will be an Error (can't await) or a Warning:

CS4032 The 'await' operator can only be used within an async method.

Is obvious, you should have used a *Async method. But do not 'fix' it by using async void or .Result.

CS1998 This async method lacks 'await' operators and will ...

means you should not have used the *Async method.

CS4014 Because this call is not awaited, ...

means you are not awaiting something you should.

Upvotes: 4

Related Questions