9

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

 3 years ago
source link: https://dzone.com/articles/blazor-how-tos-status-from-a-background-task
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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 tounsubscribefrom 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK