BlazorWorker
Library for creating DotNet Web Worker threads/multithreading in Client side Blazor
Install / Use
/learn @Tewr/BlazorWorkerREADME
BlazorWorker
Library that provides a simple API for exposing dotnet web workers in Client-side Blazor.
Checkout the Live demo to see the library in action.
This library is useful for
- CPU-intensive tasks that merit parallel execution without blocking the UI
- Executing code in an isolated process
Web workers, simply speaking, is a new process in the browser with a built-in message bus.
To people coming from the .NET world, an analogy for what this library does is calling Process.Start to start a new .NET process, and expose a message bus to communicate with it.
The library comes in two flavours, one built on top of the other:
- A high-level expressions-based API that hides the complexity of messaging, using strongly typed service definitions. Recommended for long-running tasks without too much back and forth.
- A low-level API to communicate with a new .NET process in a web worker. Uses plain strings for communication. Recommended for chatty high-performance communication.
Supported framework versions
| .NET Version(s) targets | Supported BlazorWorker Versions | | ------------------------------- | ------------------------------- | | .NET Standard 2, .NET 5, .NET 6 | v3.x | | .NET 7 | v3.x to v5.x | | .NET 8, .NET 9, .NET 10 | v4.x and later |
Native framework multithreading
Multi-threading enthusiasts should closely monitor this tracking issue in the dotnet runtime repo, which promises threading support in ~~.net 7~~ ~~.net8~~ ~~.net9~~ ~~.net10~~ .net11, projected for nov 2026.
Since .net7-rc2 there is an experimental multithreading api, read about it here
Tewr.BlazorWorker.BackgroundService Installation
Nuget package:
Install-Package Tewr.BlazorWorker.BackgroundService
Add the following line in Program.cs:
builder.Services.AddWorkerFactory();
And then in a .razor View:
@using BlazorWorker.BackgroundServiceFactory
@using BlazorWorker.Core
@inject IWorkerFactory workerFactory
Tewr.BlazorWorker.BackgroundService Notes
A high-level API that abstracts the complexity of messaging by exposing a strongly typed interface with Expressions. Mimics Task.Run as closely as possible to enable multi-threading.
The starting point of a BlazorWorker in this context is a service class that must be defined by the caller. The methods that you expose in your service can then be called from the IWorkerBackgroundService interface. Methods and method parameters must be public, or the expression serializer will throw an exception. If you declare a public event on your service, it can be used to call back into blazor during a method execution (useful for progress reporting).
Each worker process can contain multiple service classes, but each single worker can work with only one thread. For multiple concurrent threads, you must create a new worker for each (see the Multithreading example for a way of organizing this.
Example (see the demo project for a fully working example):
// MyCPUIntensiveService.cs
public class MyCPUIntensiveService {
public int MyMethod(int parameter) {
int i = 1;
while(i < 5000000) i += (i*parameter);
return i;
}
}
// .razor view
@using BlazorWorker.BackgroundServiceFactory
@using BlazorWorker.Core
@inject IWorkerFactory workerFactory
<button @onclick="OnClick">Test!</button>
@code {
int parameterValue = 5;
public async Task OnClick(EventArgs _)
{
// Create worker.
var worker = await workerFactory.CreateAsync();
// Create service reference. For most scenarios, it's safe (and best) to keep this
// reference around somewhere to avoid the startup cost.
var service = await worker.CreateBackgroundServiceAsync<MyCPUIntensiveService>();
// Reference that live outside of the current scope should not be passed into the expression.
// To circumvent this, create a scope-local variable like this, and pass the local variable.
var localParameterValue = this.parameterValue;
var result = await service.RunAsync(s => s.MyMethod(localParameterValue));
}
}
Tewr.BlazorWorker.BackgroundService: Configure serialization (starting v4.1.0)
Expressions are being serialized with Serialize.Linq by default before being sent over to the worker. Sometimes, when using structured data, particularily when using abstract classes, you may get an exception. The exception message may mention something like "Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.". You can follow the first advice by adding KnownTypeAttribute to some classes, but sometimes it wont be possible (maybe the classes aren't yours).
To follow the second advice, "passing types to DataContractSerializer", you may configure serialization more in detail. BlazorWorker.BackgroundService uses a default implementation of IExpressionSerializer to serialize expressions. You may provide a custom implementation, and pass the type of this class to IWorkerInitOptions.UseCustomExpressionSerializer when initializing your service. The most common configuration will be to add some types to AddKnownTypes, so for that paricular scenario you can use a provided base class as shown below.
Setup your service like this: https://github.com/Tewr/BlazorWorker/blob/4c9f1320c22f90e4d6e954238ad9b1e0e3f627ce/src/BlazorWorker.Demo/SharedPages/Pages/ComplexSerialization.razor#L93-L94
The custom serializer can look like this if you just want to use AddKnownTypes, by using the base class: https://github.com/Tewr/BlazorWorker/blob/4c9f1320c22f90e4d6e954238ad9b1e0e3f627ce/src/BlazorWorker.Demo/SharedPages/Shared/CustomExpressionSerializer.cs#L13-L17
Or a fully custom implementation can be used, or if you want to change Serialize.Linq to some other library): https://github.com/Tewr/BlazorWorker/blob/4c9f1320c22f90e4d6e954238ad9b1e0e3f627ce/src/BlazorWorker.Demo/SharedPages/Shared/CustomExpressionSerializer.cs#L22-L45
Special thanks to @petertorocsik for a first idea and implementation of this mechanism.
More Culture!
Since .net6.0, the runtime defaults to the invariant culture, and new cultures cannot be used or created by default. You may get the exception with the message "Only the invariant culture is supported in globalization-invariant mode", commonly when using third-party libraries that make use of any culture other than the invariant one.
You may try to circument any problems relating to this by changing the options.
var serviceInstance4 = await worker.CreateBackgroundServiceAsync<MyService>(
options => options
// Allow custom cultures by setting this to zero
.SetEnv("DOTNET_SYSTEM_GLOBALIZATION_PREDEFINED_CULTURES_ONLY", "0")
);
Since v5.0.0, the environment variable DOTNET_SYSTEM_GLOBALIZATION_INVARIANT defaults to 0, due to some changes in behaviour in net9 compared to previous framework versions.
Read more here on culture options.
Injectable services
The nominal use case is that the Service class specifies a parameterle
