Skip to content

Tewr/BlazorWorker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NuGet NuGet NuGet Donate

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:

  • BlazorWorker.BackgroundService: A high-level expressions-based API that hides the complexity of messaging
  • BlazorWorker.Core: A low-level API to communicate with a new .NET process in a web worker

Net 5 & 6 Support

.netstandard2, .net5 and .net6 can be used as targets with BlazorWorker version v3.x, but new features will not be developed for these targets due to the breaking changes in .net7.

Net 7 & 8 Support

.net7 & .net8 targets can be used from release v4.0.0 and higher versions.

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, projected for nov 2025.

.net7-rc2 has an experimental multithreading api, read about it here

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

BlazorWorker.BackgroundService

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 paramters 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));
    }
}

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 messsage 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:

backgroundService = await worker.CreateBackgroundServiceAsync<ComplexService>(options
=> options.UseCustomExpressionSerializer(typeof(CustomSerializeLinqExpressionJsonSerializer)));

The custom serializer can look like this if you just want to use AddKnownTypes, by using the base class:

public class CustomSerializeLinqExpressionJsonSerializer : SerializeLinqExpressionJsonSerializerBase
{
public override Type[] GetKnownTypes() =>
[typeof(ComplexServiceArg), typeof(ComplexServiceResponse), typeof(OhLookARecord)];
}

Or a fully custom implementation can be used, or if you want to change Serialize.Linq to some other library):

public class CustomExpressionSerializer : IExpressionSerializer
{
private readonly ExpressionSerializer serializer;
public CustomExpressionSerializer()
{
var specificSerializer = new JsonSerializer();
specificSerializer.AddKnownType(typeof(ComplexServiceArg));
specificSerializer.AddKnownType(typeof(ComplexServiceResponse));
specificSerializer.AddKnownType(typeof(OhLookARecord));
this.serializer = new ExpressionSerializer(specificSerializer);
}
public Expression Deserialize(string expressionString)
{
return serializer.DeserializeText(expressionString);
}
public string Serialize(Expression expression)
{
return serializer.SerializeText(expression);
}
}

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 default 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")
  );

Read more here on culture options.

Injectable services

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 from IWorker.PostMessageAsync, and provides messages using IWorker.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.

Core package

NuGet

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.

Extensions.JSRuntime package

NuGet

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.