Skip to content

[browser][MT][API Proposal]: Provide an API to transfer JS objects between main browser thread and JSWebWorker contexts #102011

Open
@kekekeks

Description

@kekekeks

Background and motivation

Certain javascript objects are intended to be transferred to web worker scope rather than be just copied. Notable examples are OffscreenCanvas, streams, video frames, webrtc, etc.

API Proposal

namespace System.Runtime.InteropServices.JavaScript;

public class JSHost
{
    /// <summary>
    /// Transfers the object from its context into the current scope via postMessage API.
    ///  Passed JSObject instance immediately becomes disposed and is no longer usable after this call.
    ///  Users should await the task and use the transferred object instead.
    /// </summary>
    /// <param name="object">The object to be transferred into the current context.</param>
    /// <returns>A task that completes with a reference to the new object in the current context.</returns>
    public Task<JSObject> TransferToCurrentContextAsync(JSObject object);
}

API Usage

JSObject offscreenCanvas = JsImportSafeNativeMethods.TransferControlToOffscreen(canvas);
JSWebWorker.RunAsync(() =>
{
     var canvas = await JSHost.TransferToCurrentContextAsync(offscreenCanvas);
     // use canvas
});

Alternative Designs

Provide a way to add handlers to custom messages for message event and postMessage API of Worker /DedicatedWorkerGlobalScope objects

@pavelsavara

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions