DEV Community

Cover image for Stop freezing your Blazor UI: run slow C# in a Web Worker
Todd Tanner
Todd Tanner

Posted on Originally published at spawndev.com

Stop freezing your Blazor UI: run slow C# in a Web Worker

Live demo | Full example on GitHub

You add a button that does some real work. Someone clicks it, and the whole page stops. Nothing scrolls and no other button responds until the work is done.

A Blazor WebAssembly app normally runs its C# on the same thread the browser uses to draw the page. While your loop runs, the browser cannot draw.

Task.Run does not help here. Without WebAssembly threading, it queues the work on that same thread.

The browser's answer is a Web Worker: a separate thread with its own memory. In this article we move a slow C# method into one and measure what changes. You need the .NET 10 SDK and a browser.

Something slow

This counts prime numbers the hard way:

namespace WebWorkers;

public static class Primes
{
    /// <summary>Counts the primes up to and including <paramref name="limit"/>. Slow on purpose.</summary>
    public static int Count(int limit)
    {
        var count = 0;
        for (var n = 2; n <= limit; n++)
        {
            var isPrime = true;
            for (var d = 2; (long)d * d <= n; d++)
            {
                if (n % d == 0)
                {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) count++;
        }
        return count;
    }
}
Enter fullscreen mode Exit fullscreen mode

Set up

dotnet new blazorwasm -o WebWorkers --empty
cd WebWorkers
dotnet add package SpawnDev.SpawnJS
dotnet add package SpawnDev.SpawnJS.Blazor
dotnet add package SpawnDev.SpawnJS.WebWorkers
Enter fullscreen mode Exit fullscreen mode

Save the class above as Primes.cs, then replace Program.cs:

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using SpawnDev.SpawnJS;
using SpawnDev.SpawnJS.WebWorkers;
using WebWorkers;

var builder = WebAssemblyHostBuilder.CreateDefault(args);

builder.Services.AddSpawnJSRuntime(out var JS);
builder.Services.AddWebWorkerService();

// A worker runs this file too, but it has no page to render into.
if (JS.IsWindow)
{
    builder.RootComponents.Add<App>("#app");
}

await builder.Build().SpawnJSRunAsync();
Enter fullscreen mode Exit fullscreen mode

A worker starts a second copy of your app, so it runs Program.cs too. It has no page to draw on, which is why the root component is added only when JS.IsWindow is true.

The build may show warning CA1416 on two of these lines. It says the calls need a browser, which a Blazor WebAssembly app is, so you can ignore it.

Add these lines to _Imports.razor:

@using SpawnDev.SpawnJS
@using SpawnDev.SpawnJS.WebWorkers
Enter fullscreen mode Exit fullscreen mode

Run it on the page

The page shows a clock with milliseconds. The clock runs on the same thread as the rest of the page, so when the page freezes, the clock stops:

// The clock runs on the page's thread, so it stops whenever that thread is busy.
async Task RunClock()
{
    var sinceUpdate = Stopwatch.StartNew();
    while (true)
    {
        clock = DateTime.Now.ToString("HH:mm:ss.fff");
        StateHasChanged();
        await Task.Delay(30);
        if (sinceUpdate.Elapsed > longestStop) longestStop = sinceUpdate.Elapsed;
        sinceUpdate.Restart();
    }
}
Enter fullscreen mode Exit fullscreen mode

The first button calls the method directly:

async Task CountHere()
{
    await Start();
    var count = Primes.Count(Limit);
    await Finish(count);
}
Enter fullscreen mode Exit fullscreen mode

Start and Finish update the message and measure how long the clock stopped. Click the button and watch: the clock stops dead until the answer appears.

Run it in a worker

The second button changes one line:

async Task CountInWorker()
{
    await Start();
    var count = await Workers.TaskPool.Run(() => Primes.Count(Limit));
    await Finish(count);
}
Enter fullscreen mode Exit fullscreen mode

Workers is the injected WebWorkerService. TaskPool.Run takes the call you want to make, sends the method and its arguments to a worker, and gives you the result as a Task. Click it and the clock keeps running.

What we measured

The page reports how long the clock stopped while it counted the primes up to six million:

Button Clock stopped for
Count on the page about 3 seconds
Count in a worker about 0.05 seconds

The clock waits 30 ms between updates, so 0.05 seconds is close to its normal pace. These are from one desktop PC in headless Chromium. Your times will differ, and slower devices freeze for longer.

The worker does not make the counting itself faster. It moves the work to where it does not block the page.

What to know first

  • The first call is slower. A worker has to start its own copy of your app.
  • Workers do not share your variables. Each has its own memory, so a static field you set on the page is not set in the worker. Pass what the method needs as arguments.
  • Arguments and results are sent between threads. Small values are cheap. For large arrays, see transferable objects in the WebWorkers README.
  • No special server headers are needed for this example.

The whole page

Replace Pages/Home.razor with this:

@page "/"
@using System.Diagnostics
@inject WebWorkerService Workers

<main>
    <h1>Does the clock stop?</h1>
    <p>Each button counts the primes up to @Limit.ToString("N0"). It is the same C# method, run in two different places. Watch the clock while it works.</p>
    <p id="clock">@clock</p>
    <button id="here" disabled="@busy" @onclick="CountHere">Count on the page</button>
    <button id="worker" disabled="@busy" @onclick="CountInWorker">Count in a worker</button>
    <p id="result" role="status">@result</p>
</main>

@code {
    const int Limit = 6_000_000;
    string clock = "";
    string result = "";
    bool busy;
    TimeSpan longestStop;

    protected override void OnInitialized() => _ = RunClock();

    // The clock runs on the page's thread, so it stops whenever that thread is busy.
    async Task RunClock()
    {
        var sinceUpdate = Stopwatch.StartNew();
        while (true)
        {
            clock = DateTime.Now.ToString("HH:mm:ss.fff");
            StateHasChanged();
            await Task.Delay(30);
            if (sinceUpdate.Elapsed > longestStop) longestStop = sinceUpdate.Elapsed;
            sinceUpdate.Restart();
        }
    }

    async Task CountHere()
    {
        await Start();
        var count = Primes.Count(Limit);
        await Finish(count);
    }

    async Task CountInWorker()
    {
        await Start();
        var count = await Workers.TaskPool.Run(() => Primes.Count(Limit));
        await Finish(count);
    }

    async Task Start()
    {
        busy = true;
        result = "Counting...";
        await Task.Delay(100); // let the page draw before the work starts
        longestStop = TimeSpan.Zero;
    }

    async Task Finish(int count)
    {
        await Task.Delay(100); // let the clock notice a stop that has just ended
        result = $"Found {count:N0} primes. The clock's longest stop was {longestStop.TotalSeconds:F2} seconds.";
        busy = false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Run it

Run dotnet run in your project, or clone the finished one:

git clone https://github.com/LostBeard/SpawnDev.Examples
cd SpawnDev.Examples/WebWorkers
dotnet run
Enter fullscreen mode Exit fullscreen mode

Top comments (0)