Search code examples
blazorblazor-client-sideblazor-webassembly

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

  • What's the difference using async void and async Task in Method signature?
  • Why does the async void doesn't update the UI immediately?

Solution

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