In a browser-based Blazor WebAssembly app, running heavy C# work—such as parsing large CSV grade sheets or crunching statistics—on the main thread can freeze button clicks and animations. In .NET 11, Microsoft officially introduces the blazorwebworker template with InvokeVoidAsync and CancellationToken support so you can run [JSExport] C# logic inside a dedicated browser Web Worker while keeping your UI smooth.
Blazor UI + WebWorkerClient ↔ InvokeAsync + CancellationToken ↔ blazorwebworker ([JSExport])
1. Create a Blazor App and Web Worker Project
Install the WebAssembly workloads, scaffold your Blazor WebAssembly app alongside a blazorwebworker project, and reference the worker library:
dotnet workload install wasm-tools
dotnet workload install wasm-experimental
dotnet new blazorwasm -n StudentPortal
dotnet new blazorwebworker -n StudentWorker
cd StudentPortal
dotnet add reference ../StudentWorker/StudentWorker.csproj
2. Export a Worker Method with [JSExport]
Inside your StudentWorker project, mark static methods in a static partial class with [JSExport] so the browser worker can run them off the UI thread:
using System.Runtime.InteropServices.JavaScript;
namespace StudentWorker;
public static partial class GradeWorkerMethods
{
[JSExport]
public static long SumLargeSeries(int limit)
{
long total = 0;
for (int i = 1; i <= limit; i++)
{
total += i;
}
return total;
}
}
3. Call WebWorkerClient with CancellationToken in Razor
In your Razor page, inject WebWorkerClient and call InvokeAsync (or InvokeVoidAsync for fire-and-forget work) with a timeout CancellationToken:
@page "/"
@inject WebWorkerClient WorkerClient
<button class="btn btn-primary" @onclick="RunCalculation">Calculate in Worker</button>
<p>Result: @_result</p>
<p>Status: @_status</p>
@code {
private long _result;
private string _status = "Ready";
private async Task RunCalculation()
{
_status = "Running in background Web Worker...";
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
try
{
_result = await WorkerClient.InvokeAsync<int, long>(
"GradeWorkerMethods.SumLargeSeries", 50_000_000, cts.Token);
_status = "Done without freezing the UI!";
}
catch (OperationCanceledException)
{
_status = "Worker timed out or was canceled.";
}
}
}
Practice
- Add a
voidmethod marked with[JSExport]and call it usingWorkerClient.InvokeVoidAsync(...). - Add a Cancel button wired to a shared
CancellationTokenSourceso users can stop a long task early. - Notice how Blazor Server apps in .NET 11 also offer circuit auto-pause (
Microsoft.AspNetCore.Components.Server.AutoPause) to free server memory on inactive tabs.
Continue learning: .NET Core and ASP.NET Core: Student Learning Path.
References: ASP.NET Core Blazor Documentation (Microsoft Learn).
No comments:
Post a Comment
Please do not enter any spam link in the comment box.