WebWorker
The WebWorker component runs a piece of JavaScript in a Web Worker, a background thread in the user's browser, and connects it to your server code:
- the server sends data to the worker with
SendMessage, and the worker receives it in itsonmessagehandler; - the worker sends results back with
postMessage, which fires thePostMessageevent on the server.
Use it for CPU-heavy work that can run on the client without freezing the page, such as parsing or transforming large data, image processing, hashing or client-side encryption, while the rest of the application stays responsive and the server does less work.
Installation
The extension isn't published on NuGet. Build Wisej.Ext.WebWorker from the source repository and reference the assembly from your Wisej.NET project. It targets .NET Framework 4.8 and .NET 8 or later. After a rebuild, WebWorker appears in the Visual Studio toolbox as a component.
Getting started
A worker that doubles the numbers it receives:
- C#
- VB.NET
using Wisej.Ext.WebWorker;
private WebWorker webWorker;
public Page1()
{
InitializeComponent();
this.webWorker = new WebWorker(this.components);
this.webWorker.JavaScript = @"
onmessage = function (e) {
postMessage(e.data * 2);
};";
this.webWorker.PostMessage += this.webWorker_PostMessage;
}
private void buttonCalculate_Click(object sender, EventArgs e)
{
this.webWorker.SendMessage(21);
}
private void webWorker_PostMessage(object sender, WebWorkerPostMessageEventArgs e)
{
AlertBox.Show($"Result: {e.Data}"); // Result: 42
}
Imports Wisej.Ext.WebWorker
Private WithEvents webWorker As WebWorker
Public Sub New()
InitializeComponent()
Me.webWorker = New WebWorker(Me.components)
Me.webWorker.JavaScript = "
onmessage = function (e) {
postMessage(e.data * 2);
};"
End Sub
Private Sub ButtonCalculate_Click(sender As Object, e As EventArgs) Handles ButtonCalculate.Click
Me.webWorker.SendMessage(21)
End Sub
Private Sub webWorker_PostMessage(sender As Object, e As WebWorkerPostMessageEventArgs) Handles webWorker.PostMessage
AlertBox.Show($"Result: {e.Data}") ' Result: 42
End Sub
The worker starts the first time you call SendMessage, and it keeps running and handling messages until you terminate it, change its script, or the page closes.
The worker script
Set the script in one of two ways:
| Property | What it holds |
|---|---|
JavaScript | The script itself. It takes precedence when both are set. In the designer, it opens the JavaScript editor. |
JavaScriptSource | The name of a .js file. The component looks for it first in the application folder, and then among the embedded resources of the calling assembly (matching the end of the resource name). |
The component serves the script to the browser through its own URL, so the file doesn't need to be publicly reachable. Inside the script, the standard worker API applies: onmessage receives what the server sends (in e.data), postMessage(value) sends a result back, and importScripts(url) loads libraries.
Changing JavaScript or JavaScriptSource, or calling Update(), reloads the script: the running worker is terminated and a new one starts with the new code.
Exchanging data
Anything you pass to SendMessage is serialized to JSON on its way to the browser, so you can send numbers, strings, arrays or whole objects. On the way back, WebWorkerPostMessageEventArgs.Data holds whatever the worker posted. Objects arrive as dynamic objects:
- C#
- VB.NET
// worker script:
// onmessage = function (e) {
// var sum = e.data.values.reduce(function (a, b) { return a + b; }, 0);
// postMessage({ name: e.data.name, sum: sum });
// };
private void buttonSum_Click(object sender, EventArgs e)
{
this.webWorker.SendMessage(new { name = "Totals", values = new[] { 1, 2, 3, 4, 5 } });
}
private void webWorker_PostMessage(object sender, WebWorkerPostMessageEventArgs e)
{
dynamic result = e.Data;
AlertBox.Show($"{result.name}: {result.sum}"); // Totals: 15
}
' worker script:
' onmessage = function (e) {
' var sum = e.data.values.reduce(function (a, b) { return a + b; }, 0);
' postMessage({ name: e.data.name, sum: sum });
' };
Private Sub ButtonSum_Click(sender As Object, e As EventArgs) Handles ButtonSum.Click
Me.webWorker.SendMessage(New With {.name = "Totals", .values = {1, 2, 3, 4, 5}})
End Sub
Private Sub webWorker_PostMessage(sender As Object, e As WebWorkerPostMessageEventArgs) Handles webWorker.PostMessage
Dim result As Object = e.Data
AlertBox.Show($"{result.name}: {result.sum}") ' Totals: 15
End Sub
A worker can call postMessage as often as it likes, for example to report progress, and each call fires PostMessage once.
Every message crosses the network between the browser and the server. The worker pays off when it does a lot of computing on little data, or when the data is already in the browser. Don't use it just to move large payloads back and forth.
Stopping a worker
Terminate() stops the worker immediately, without letting it finish. The next SendMessage starts a fresh one:
private void buttonCancel_Click(object sender, EventArgs e)
{
this.webWorker.Terminate();
this.labelStatus.Text = "Canceled.";
}
Browser support
All current browsers support Web Workers. The static WebWorker.IsSupported property returns false only when the current browser reports that it lacks them. In that case SendMessage does nothing, so keep a server-side fallback if you must support such browsers.
The worker's code is sent to the browser, where the user can read it and change it, and PostMessage delivers whatever the browser posts back. Don't put secrets in a worker script. Treat the results like any other client input, and validate them before relying on them for anything that matters, such as prices, permissions or stored data.
API reference
WebWorkerWebWorkerPostMessageEventArgsandWebWorkerPostMessageEventHandler- The whole
Wisej.Ext.WebWorkernamespace