SpawnDev.BlazorJS.WebWorkers 1.3.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package SpawnDev.BlazorJS.WebWorkers --version 1.3.0
NuGet\Install-Package SpawnDev.BlazorJS.WebWorkers -Version 1.3.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SpawnDev.BlazorJS.WebWorkers" Version="1.3.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add SpawnDev.BlazorJS.WebWorkers --version 1.3.0
#r "nuget: SpawnDev.BlazorJS.WebWorkers, 1.3.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install SpawnDev.BlazorJS.WebWorkers as a Cake Addin
#addin nuget:?package=SpawnDev.BlazorJS.WebWorkers&version=1.3.0

// Install SpawnDev.BlazorJS.WebWorkers as a Cake Tool
#tool nuget:?package=SpawnDev.BlazorJS.WebWorkers&version=1.3.0

SpawnDev.BlazorJS

NuGet

Supports .Net 6 and .Net 7

An easy Javascript interop library desgined specifcally for client side Blazor.

  • Use Javascript libraries in Blazor without writing any Javascript code.
  • Alternative access to IJSRuntime JS is globally available without injection and is usable on the first line of Program.cs
  • Get and set global proeprties via JS.Set and JS.Get
  • Create new Javascript objects with JS.New
  • Get and set object properties via IJSInProcessObjectReference extended methods
  • Create Callbacks that can be sent to Javascript event listeners or assigned to javascript variables
  • Easily call Services in separate threads with WebWorkers and SharedWebWorkers

NOTE: The below code shows quick examples. Some objects implement IDisposable, such as all JSObject, IJSInProcessObjectReference, and Callback, and need to be disposed when no longer used.

Firefox WebWorkers note:
Firefox does not support dynamic modules in workers, which originally made BlazorJS.WebWorkers fail in that browser. I wrote code that changes the scripts on the fly before they are loaded to workaround this limitation until Firefox finishes worker module intergration.

https://bugzilla.mozilla.org/show_bug.cgi?id=1540913#c6
https://bugzilla.mozilla.org/show_bug.cgi?id=1247687

JS

// Get Set
var innerHeight = JS.Get<int>("window.innerHeight");
JS.Set("document.title", "Hello World!");

// Call
var item = JS.Call<string?>("localStorage.getItem", "itemName");
JS.CallVoid("addEventListener", "resize", Callback.Create(() => Console.WriteLine("WindowResized"), _callBacks));

IJSInProcessObjectReference extended

// Get Set
var window = JS.Get<IJSInProcessObjectReference>("window");
window.Set("myVar", 5);
var myVar = window.Get<int>("myVar");

// Call
window.CallVoid("addEventListener", "resize", Callback.Create(() => Console.WriteLine("WindowResized")));

Create a new Javascript object

var worker = JS.New("Worker", myWorkerScript);

Pass callbacks to Javascript

JS.Set("testCallback", Callback.Create<string>((strArg) => {
    Console.WriteLine($"Javascript sent: {strArg}");
    // this prints "Hello callback!"
}));
// in Javascript
testCallback('Hello callback!');

JSObject

JSObjects are wrappers around IJSInProcessReference objects that can be passed to and from Javascript and allow strongly typed access to the underlying object.

Use the extended functions of IJSInProcessObjectReference to work with Javascript objects or use the growing library of over 100 of the most common Javascript objects, including ones for Window, HTMLDocument, WebStorage (locaStorage and sessionStorage), WebGL, WebRTC, and more in SpawnDev.BlazorJS.JSObjects. JSObjects are wrappers around IJSInProcessObjectReference that allow strongly typed use.

Custom JSObjects

Implement your own JSObject classes for Javascript objects not already available in the BlazorJS.JSObjects library.

Instead of this (simple but not as reusable)

var audio = JS.New("Audio", "https://some_audio_online");
audio.CallVoid("play");

Do this...
Create a custom JSObject class

[JsonConverter(typeof(JSObjectConverter<Audio>))]
public class Audio : JSObject
{
    public Audio(IJSInProcessObjectReference _ref) : base(_ref) { }
    public Audio(string url) : base(JS.New("Audio", url)) { }
    public void Play() => JSRef.CallVoid("play");
}

Then use your new object

var audio = new Audio("https://some_audio_online");
audio.Play();

SpawnDev.BlazorJS.WebWorkers

NuGet

Run CPU intensive tasks on a dedicated worker or on a shared worker with WebWorkers!

Example WebWorkerService setup and usage

// Program.cs
...
using SpawnDev.BlazorJS;
using SpawnDev.BlazorJS.WebWorkers;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
if (JS.IsWindow)
{
    // we can skip adding dom objects in non UI threads
    builder.RootComponents.Add<App>("#app");
    builder.RootComponents.Add<HeadOutlet>("head::after");
}
// add services
builder.Services.AddSingleton((sp) => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
// SpawnDev.BlazorJS.WebWorkers
builder.Services.AddSingleton<WebWorkerService>();
// app specific services...
builder.Services.AddSingleton<MathsService>();
// build 
WebAssemblyHost host = builder.Build();
// init WebWorkerService
var workerService = host.Services.GetRequiredService<WebWorkerService>();
await workerService.InitAsync();
await host.RunAsync();

WebWorker


// Create a WebWorker
var webWorker = await workerService.GetWebWorker();

// Call a registered service on the worker thread with your arguments
// Action types can be passed for progress reporting
var result = await webWorker.InvokeAsync<MathsService, string>("CalculatePiWithActionProgress", piDecimalPlaces, new Action<int>((i) =>
{
    piProgress = i;
    StateHasChanged();
}));

SharedWebWorker

Calling GetSharedWebWorker in another window with the same sharedWorkerName will return the same SharedWebWorker

// Create or get SHaredWebWorker with the provided sharedWorkerName
var sharedWebWorker = await workerService.GetSharedWebWorker("workername");

// Just like WebWorker but shared
// Call a registered service on the worker thread with your arguments
var result = await sharedWebWorker.InvokeAsync<MathsService, string>("CalculatePiWithActionProgress", piDecimalPlaces, new Action<int>((i) =>
{
    piProgress = i;
    StateHasChanged();
}));

Send events

// Optionally listen for event messages
worker.OnMessage += (sender, msg) =>
{
    if (msg.TargetName == "progress")
    {
        PiProgress msgData = msg.GetData<PiProgress>();
        piProgress = msgData.Progress;
        StateHasChanged();
    }
};

// From SharedWebWorker or WebWorker threads send an event to conencted parents
workerService.SendEventToParents("progress", new PiProgress { Progress = piProgress });

// Or on send an event to a connected worker
webWorker.SendEvent("progress", new PiProgress { Progress = piProgress });

Worker Transferable JSObjects

When working with workers in Javascript you can optionally tell Javascript (via the MessagePort.postMessage method) to transfer some of the objects instead of copying them.

WebWorkerService, when calling services on a worker, will transfer any transfaerable types by default. To disable the transfering of a return value, paramter, or proprty use the WorkerTransferAttribute.

Example

        public class ProcessFrameResult
        {
            [WorkerTransfer(false)]
            public ArrayBuffer? ArrayBuffer { get; set; }
            public byte[]? HomorgraphyBytes { get; set; }
        }

        [return: WorkerTransfer(false)]
        public async Task<ProcessFrameResult?> ProcessFrame([WorkerTransfer(false)] ArrayBuffer? frameBuffer, int width, int height, int _canny0, int _canny1, double _needlePatternSize)
        {
            // ...
            return null;
        }

In the above example; the WorkerTransferAttribute on the return type set to false will prevent all properties of the return type from being transferred.

Transferable JSObject types

ArrayBuffer
MessagePort
ReadableStream
WritableStream
TransformStream
AudioData
ImageBitmap
VideoFrame
OffscreenCanvas
RTCDataChannel

Support

Inspired by Tewr's BlazorWorker implementation. Thank you! I wrote my implementation from scratch as I needed workers in .Net 7.
https://github.com/Tewr/BlazorWorker

BlazorJS and WebWorkers Demo
https://blazorjs.spawndev.com/

Buy me a coffee

paypal

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.2.67 54 3/27/2024
2.2.66 53 3/24/2024
2.2.65 53 3/21/2024
2.2.64 128 3/11/2024
2.2.63 83 3/9/2024
2.2.62 99 3/7/2024
2.2.61 95 3/6/2024
2.2.60 87 3/6/2024
2.2.58 130 3/2/2024
2.2.57 113 2/24/2024
2.2.56 109 2/18/2024
2.2.55 81 2/17/2024
2.2.53 91 2/15/2024
2.2.52 87 2/15/2024
2.2.51 86 2/15/2024
2.2.49 227 2/2/2024
2.2.48 531 12/29/2023
2.2.47 125 12/20/2023
2.2.46 96 12/15/2023
2.2.45 87 12/10/2023
2.2.44 93 12/10/2023
2.2.42 89 12/9/2023
2.2.41 94 12/9/2023
2.2.40 70 12/8/2023
2.2.38 472 11/21/2023
2.2.37 130 11/16/2023
2.2.36 73 11/16/2023
2.2.35 109 11/14/2023
2.2.34 93 11/13/2023
2.2.33 60 11/10/2023
2.2.32 69 11/10/2023
2.2.31 64 11/9/2023
2.2.28 78 11/7/2023
2.2.27 130 10/31/2023
2.2.26 143 10/22/2023
2.2.25 76 10/20/2023
2.2.24 78 10/20/2023
2.2.23 81 10/20/2023
2.2.22 78 10/20/2023
2.2.21 72 10/20/2023
2.2.20 67 10/19/2023
2.2.19 71 10/19/2023
2.2.18 75 10/19/2023
2.2.17 163 10/13/2023
2.2.16 471 10/12/2023
2.2.15 67 10/12/2023
2.2.14 90 10/5/2023
2.2.13 72 10/5/2023
2.2.12 71 10/5/2023
2.2.11 176 10/3/2023
2.2.10 146 9/18/2023
2.2.9 70 9/18/2023
2.2.8 236 9/14/2023
2.2.7 79 9/13/2023
2.2.6 2,880 9/6/2023
2.2.5 121 8/30/2023
2.2.4 132 8/26/2023
2.2.3 102 8/20/2023
2.2.2 89 8/18/2023
2.2.1 101 8/11/2023
2.2.0 182 7/17/2023
2.1.15 106 5/26/2023
2.1.14 96 5/20/2023
2.1.13 105 4/26/2023
2.1.12 162 4/21/2023
2.1.11 91 4/19/2023
2.1.10 108 4/19/2023
2.1.8 124 4/10/2023
2.1.7 141 3/27/2023
2.1.6 121 3/24/2023
2.1.5 122 3/23/2023
2.1.4 123 3/23/2023
2.1.3 130 3/23/2023
2.1.2 118 3/21/2023
2.1.0 127 3/21/2023
2.0.3 127 3/21/2023
2.0.2 117 3/20/2023
2.0.1 122 3/20/2023
2.0.0 129 3/20/2023
1.9.2 132 3/14/2023
1.8.1 126 3/11/2023
1.8.0 121 3/10/2023
1.7.1 117 3/10/2023
1.7.0 110 3/8/2023
1.6.4 125 3/1/2023
1.6.3 274 1/31/2023
1.6.2 281 1/24/2023
1.6.1 290 1/11/2023
1.6.0 295 1/11/2023
1.5.0 334 12/23/2022
1.4.0 292 12/20/2022
1.3.0 304 12/16/2022
1.2.7 307 12/16/2022
1.2.5 284 12/14/2022
1.2.4.1 294 12/13/2022
1.2.4 289 12/13/2022
1.2.3 291 12/13/2022