{{announcement.body}}
{{announcement.title}}

Blazor How-To's: Status From a Background Task

DZone 's Guide to

Blazor How-To's: Status From a Background Task

In this post, you'll learn two ways to launch a background task and display its status in your Blazor app.

· Web Dev Zone ·
Free Resource

Ever wondered how would it be possible to launch a background task and display its status in your Blazor app? Well, in this post you’ll learn not one, but two ways to do it!

In the last post, we saw how easy it is to implement Conway’s Game of Life using Blazor. The code was registering a Scoped instance of the World class, which in turn was broadcasting an event every time the simulation was updated.

For those interested, I used the Scoped lifetime instead of Singleton in order to ensure that every UI client is receiving its own instance. Otherwise, everyone connecting to the app would see the same simulation.

So the first technique is indeed broadcasting the necessary events. The key here is the call to StateHasChanged(). From the docs:

StateHasChanged notifies the component that its state has changed. When applicable, calling StateHasChanged causes the component to be rerendered.

Basically, when your UI component is relying on data that gets updated outside, maybe from another thread, the system won’t be able to detect the changes. In that case, your only option is to force the re-rendering in order to get the new state on screen.

The call to StateHasChanged() will switch to the correct context and push a request to the Blazor’s rendering queue.

In the UI component, all you have to do is register to the event and call StateHasChanged(). Something like this:

C#
 




x
31


1
@code{
2
    protected override void OnInitialized()
3
    {
4
        State.OnChangeAsync += Refresh;
5
    }
6
 
          
7
    private async Task Refresh()
8
    {
9
        await InvokeAsync(StateHasChanged);
10
    }
11
 
          
12
    public void Dispose()
13
    {
14
        State.OnChangeAsync -= Refresh;
15
    }
16
}



It’s very important to unsubscribe from the event in the Dispose() method to avoid memory leaks.

This covers the first technique. The other one instead is a paradigm shift: instead of having the server notifying the client when the data is available, we have the client polling the data at regular intervals. Something like this:

C#
 




xxxxxxxxxx
1
31


1
@code{
2
    private System.Timers.Timer _timer;
3
 
          
4
    [Parameter]
5
    public double Interval { get; set; }
6
 
          
7
    protected override void OnInitialized()
8
    {
9
        _timer = new System.Timers.Timer(this.Interval);
10
 
          
11
        _timer.Elapsed += async (s, e) =>
12
        {
13
            await InvokeAsync(StateHasChanged);
14
        };
15
 
          
16
        _timer.Enabled = true;
17
    }
18
}



The core doesn’t change, we still need to use InvokeAsyncStateHasChanged. But this time, all we have to do is just initialize a timer and get the new state in its callback.

As usual, all the code is available on GitHub, feel free to take a look and send me your comments!

In this sample, I’m registering a Background Service that will increment a counter every 500 milliseconds. The Counter has a Value property and exposes also an async Event we can leverage to get notified of status changes.

Topics:
.net core ,asp.net core ,background task ,blazor ,c# ,dotnet ,tutorial ,web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}