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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a Skill-Based Agentic Reviewer with Claude Code: A Practical Guide Using Skills.MD, MCP Servers, Tools, and Tasks
  • Stop Using the ATM-Didn’t-Kill-Jobs Story to Reassure Developers About AI
  • AI Agents vs LLMs: Choosing the Right Tool for AI Tasks
  • Reducing Daily PM Overhead With a Chat-Based AI Agent

Trending

  • Every Cache Miss Is a Tiny Tax on Your Performance
  • Edge Computing in Utility IoT: Two Architecture Patterns That Actually Work
  • Building a DevOps-Ready Internal Developer Platform: A Hands-On Guide to Golden Paths, Self-Service, and Automated Delivery Pipelines
  • From Indicators to Insights: Automating IOC Enrichment Using Python and Threat Feeds

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 user avatar
David Guida
·
May. 20, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
15.8K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Building a Skill-Based Agentic Reviewer with Claude Code: A Practical Guide Using Skills.MD, MCP Servers, Tools, and Tasks
  • Stop Using the ATM-Didn’t-Kill-Jobs Story to Reassure Developers About AI
  • AI Agents vs LLMs: Choosing the Right Tool for AI Tasks
  • Reducing Daily PM Overhead With a Chat-Based AI Agent

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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