Cris M
Cris M

Reputation: 203

Blazor UI Update Async void vs Async Task

New to Blazor,

I am working with the Login via API, however I noticed that the UI doesn't update automatically.

For example: When I logged in an invalid user for the first time, the error message doesn't display, but on the 2nd try it will display correctly. Somehow has 1 click delay.

  private async void DoLogin()
  {
        var result = await API.LoginAsync(username, password);

        if (result.ResultID == 0)
        {

        }
        else
            ErrorMessage = result.ErrorMessage;
  }

Razor Component: enter image description here

When I changed it to

  private async Task DoLogin()
  {
        var result = await API.LoginAsync(username, password);

        if (result.ResultID == 0)
        {

        }
        else
            ErrorMessage = result.ErrorMessage;
  }

It is working as expected.

Can someone shed a light

Upvotes: 5

Views: 4220

Answers (2)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30036

[Polite]You just need to get your head around asynchronous programming. What's happening is that the UI rendering completes before your asynchronous task. The void routine DoLogin awaits the completion of the API call, but the methods up the call stack don't, there's no Task to await. When the API call yields control, it gets handed back up the calling stack. DoLogin waits for the Task completion before completing the rest of the code in the method, but yields to the calling method which then carries on past the call to DoLogin- in your case rendering your control.

The async Void Method pattern is fire and forget, you get no Task reference to wait on. async Task Method means you can await Method in the calling routine. You can read more here in one of my Code Project articles.

Upvotes: 5

Henk Holterman
Henk Holterman

Reputation: 273244

What's the difference using async void and async Task in Method signature?

  • An async Task (and also just Task) return is awaitable, and Blazor will use that.
  • An async void method is fire-and-forget. It should be avoided where possible.

Why does the async void doesn't update the UI immediately?

Because it executes un-observed. In this case it runs in parallel with (but slower than) the code that finishes up after the button. So the UI is updated before LoginAsync() returns.

Upvotes: 5

Related Questions