blazorblazor-server-side

Blazor Timer call async API task to update UI


I am setting up a timer in a Blazor server-side page. The goal is to call an API every x seconds and based on the return value, update the UI.

I got this code:

private string Time { get; set; }

protected override void OnInitialized()
{
    var timer = new System.Threading.Timer((_) =>
    {
        Time = DateTime.Now.ToString();
        InvokeAsync(() =>
        {
            StateHasChanged();
        });
    }, null, 0, 1000);
    base.OnInitialized();
}

This works beautifully. The UI was updated every second with the new time value. However, I can't figure out how to call an async task to get the value. I would like to replace the line:

Time = DateTime.Now.ToString();

with a line that calls the following function:

private async Task<string> GetValue()
{
    var result = await _api.GetAsync<StringDto>("/api/GetValue");
    return result.Text;
}

I've tried this line:

Time = GetValue().Result;

But I received this following error:

The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution to the Dispatcher when triggering rendering or component state.

What do I need to do to call the async method?

Thanks a bunch!


Solution

  • Try this code:

      private string Time { get; set; }
    
    protected override void OnInitialized()
    {
        base.OnInitialized();
        var timer = new System.Threading.Timer((_) =>
        {
    
            InvokeAsync( async ()  =>
            {
                Time = await GetValue();
                StateHasChanged();
            });
        }, null, 0, 1000);
    
    }
    

    Your GetValue method should be:

    private async Task<string> GetValue()
    {
        return await _api.GetAsync<StringDto>("/api/GetValue");
      
    }