Skip to content

JSReference class

A strong or weak reference to a JS value.

C#
public class JSReference : IDisposable

Public Members

namedescription
JSReference(…)Creates a new instance of a JSReference that holds a strong or weak reference to a JS value. (2 constructors)
Handle { get; }Gets the value handle, or throws an exception if access from the current thread is invalid.
IsDisposed { get; }Gets a value indicating whether the reference has been disposed.
IsWeak { get; }
SynchronizationContext { get; }Gets the synchronization context that must be used to access the referenced value.
Dispose()Releases the reference.
GetValue()Gets the referenced JS value.
MakeStrong()Changes a weak reference into a strong reference, if it is not already strong and the value is still available.
MakeWeak()Changes a strong reference into a weak reference, if it is not already weak.
Run(…)Runs an action with the referenced value, using the JSSynchronizationContext associated with the reference to switch to the JS thread (if necessary) while operating on the value.
Run<T>(…)Runs an action with the referenced value, using the JSSynchronizationContext associated with the reference to switch to the JS thread (if necessary) while operating on the value.
TryGetValue(…)Attempts to get the referenced JS value.
static TryCreateReference(…)Creates a reference to a JS value, if the value is an object, function, or symbol.
explicit operator

Protected Members

namedescription
virtual Dispose(…)
override Finalize()

Remarks

JSValue and related JS handle structs are not valid after their JSValueScope closes -- typically that is when a callback returns. Use a JSReference to maintain a reference to a JS value beyond a single scope.

A JSReference should be disposed when no longer needed; this allows the JS value to be collected by the JS GC if it has no other references. The JSReference class also has a finalizer so that the reference will be released when the C# object is GC'd. However explicit disposal is still preferable when possible.

A "strong" reference ensures the JS value is available at least until the reference is disposed. A "weak" reference does not prevent the JS value from being released collected by the JS garbage-collector, but allows the value to be optimistically retrieved until then.

See Also

Released under the MIT license