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:
- BlazorWorker.BackgroundService: A high-level API that hides the complexity of messaging
- BlazorWorker.Core: A low-level API to communicate with a new .NET process in a web worker
Multi-threading enthusiasts should closely monitor this tracking issue in the dotnet runtime repo, which promises experimental threading support in .net 7 (projected for november 2022) .net8, projected for November 2023.
.net7-rc2 has an experimental multithreading api, read about it here
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
@inject IWorkerFactory workerFactory
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 is a service class that must be defined by the caller. The public methods that you expose in your service can then be called from the IWorkerBackgroundService interface. 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) {
while(i < 5000000) i += (i*parameter);
return i;
}
}
// .razor view
@using BlazorWorker.BackgroundServiceFactory
@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));
}
}
By default, worker.CreateBackgroundServiceAsync<MyService>()
will try to guess the name of the dll that MyService
resides in (it is usually AssemblyNameOfMyService.dll).
If your dll name does not match the name of the assembly, or if your service has additional dependencies, you must provide this information in WorkerInitOptions
. If WorkerInitOptions
is provided, the default options are no longer created, so you also have to provide the dll MyService
resides in (even if it is in AssemblyNameOfMyService.dll). Examples:
// Custom service dll, additional dependency, using dll names
var serviceInstance = await worker.CreateBackgroundServiceAsync<MyService>(
options => options.AddAssemblies("MyService.dll", "MyServiceDependency.dll")
);
// Default service dll, additional dependency with dll deduced from assembly name of provided type
var serviceInstance2 = await worker.CreateBackgroundServiceAsync<MyService>(
options => options
.AddConventionalAssemblyOfService()
.AddAssemblyOf<TypeOfMyServiceDependency>()
);
// In addition to default service dll, add HttpClient as Dependency (built-in dependency definition / helper)
var serviceInstance3 = await worker.CreateBackgroundServiceAsync<MyService>(
options => options
.AddConventionalAssemblyOfService()
.AddHttpClient()
);
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 default options.
var serviceInstance4 = await worker.CreateBackgroundServiceAsync<MyService>(
options => options
.AddConventionalAssemblyOfService()
// Allow custom cultures by setting this to zero
.SetEnv("DOTNET_SYSTEM_GLOBALIZATION_PREDEFINED_CULTURES_ONLY", "0")
);
Read more here on culture options.
The nominal use case is that the Service class specifies a parameterless constructor.
If provided as constructor parameters, any of the two following services will be created and injected into the service:
HttpClient
- use to make outgoing http calls, like in blazor. Reference.IWorkerMessageService
- to communicate with the worker from blazor using messages, the lower-most level of communication. Accepts messages fromIWorker.PostMessageAsync
, and provides messages usingIWorker.IncomingMessage
. See the Core example for a use case.
These are the only services that will be injected. Any other custom dependencies has to be automated in some other way. Two extension methods simplify this by exposing the factory pattern which can be implemented with a container of your choice: IWorker.CreateBackgroundServiceUsingFactoryAsync<TFactory, TService>
and IWorkerBackgroundService.CreateBackgroundServiceAsync<TFactory, TService>
.
For an example of a full-fledged IOC Setup using Microsoft.Extensions.DependencyInjection
see the IOC example.
The Core package does not provide any serialization. This is useful for scenarios with simple API's (smaller download size), or for building a custom high-level API. See the Core example for a use case.
The JSRuntime package has primarily been developed as a middleware for supporting IndexedDB, more specifically the package Tg.Blazor.IndexedDB. See the IndexedDb example for a use case.