DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Zero Trust for Agents: A New Lens to Secure Agents
  • Python Asyncio: Understanding Concurrency With a Scraper
  • Designing AI for Long-Running Tasks: Looking Beyond More Context
  • How Long-Running ECS Tasks Survive Rolling Deployments Without Duplicating Output

Trending

  • Seven AI Adoption Failures and How to Overcome Them
  • An Introduction to OpenID AuthZEN and authzen-enforcer, a Java SDK
  • Same Prompt, Different Test: Using AI Agent Workspaces to Make Testing Repeatable
  • Hands-On: Build a Least-Privilege Sandbox for AI Agents on Kubernetes

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

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.

By 
David Guida
·
May. 20, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
16.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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 InvokeAsync + StateHasChanged. 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.

Blazor Task (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Zero Trust for Agents: A New Lens to Secure Agents
  • Python Asyncio: Understanding Concurrency With a Scraper
  • Designing AI for Long-Running Tasks: Looking Beyond More Context
  • How Long-Running ECS Tasks Survive Rolling Deployments Without Duplicating Output

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook