Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[browser][MT] - CancellationToken for JSWebWorker #96696

Merged
merged 9 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ public static void GetManagedStackTrace(JSMarshalerArgument* arguments_buffer)
// void InstallMainSynchronizationContext()
public static void InstallMainSynchronizationContext()
{
InstallWebWorkerInterop(true);
InstallWebWorkerInterop(true, CancellationToken.None);
}

#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,9 @@ public static void LoadSatelliteAssembly(byte[] dllBytes)
}

#if FEATURE_WASM_THREADS
public static void InstallWebWorkerInterop(bool isMainThread)
public static JSSynchronizationContext InstallWebWorkerInterop(bool isMainThread, CancellationToken cancellationToken)
{
var ctx = new JSSynchronizationContext(isMainThread);
var ctx = new JSSynchronizationContext(isMainThread, cancellationToken);
ctx.previousSynchronizationContext = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(ctx);

Expand All @@ -226,6 +226,8 @@ public static void InstallWebWorkerInterop(bool isMainThread)
ctx.AwaitNewData();

Interop.Runtime.InstallWebWorkerInterop(proxyContext.ContextHandle);

return ctx;
}

public static void UninstallWebWorkerInterop()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ public unsafe void ReleasePromiseHolder(nint holderGCHandle)
{
throw new InvalidOperationException("ReleasePromiseHolder expected PromiseHolder " + holderGCHandle);
}
holder.IsDisposed = true;
}
else
{
Expand All @@ -367,9 +368,9 @@ public unsafe void ReleasePromiseHolder(nint holderGCHandle)
{
throw new InvalidOperationException("ReleasePromiseHolder expected PromiseHolder" + holderGCHandle);
}
holder.IsDisposed = true;
handle.Free();
}
holder.IsDisposed = true;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using System.Threading;
using System.Threading.Channels;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using WorkItemQueueType = System.Threading.Channels.Channel<System.Runtime.InteropServices.JavaScript.JSSynchronizationContext.WorkItem>;

namespace System.Runtime.InteropServices.JavaScript
Expand All @@ -26,6 +25,8 @@ internal sealed class JSSynchronizationContext : SynchronizationContext

internal SynchronizationContext? previousSynchronizationContext;
internal bool _isDisposed;
internal bool _isCancellationRequested;
private CancellationTokenRegistration _cancellationTokenRegistration;

internal readonly struct WorkItem
{
Expand All @@ -41,11 +42,16 @@ public WorkItem(SendOrPostCallback callback, object? data, ManualResetEventSlim?
}
}

public JSSynchronizationContext(bool isMainThread)
public JSSynchronizationContext(bool isMainThread, CancellationToken cancellationToken)
{
ProxyContext = new JSProxyContext(isMainThread, this);
Queue = Channel.CreateUnbounded<WorkItem>(new UnboundedChannelOptions { SingleWriter = false, SingleReader = true, AllowSynchronousContinuations = true });
_DataIsAvailable = DataIsAvailable;
_cancellationTokenRegistration = cancellationToken.Register(() =>
{
_isCancellationRequested=true;
Queue.Writer.TryComplete();
});
}

internal JSSynchronizationContext(JSProxyContext proxyContext, WorkItemQueueType queue, Action dataIsAvailable)
Expand All @@ -62,14 +68,19 @@ public override SynchronizationContext CreateCopy()

internal void AwaitNewData()
{
if (_isDisposed)
if (_isDisposed || _isCancellationRequested)
{
// FIXME: there could be abandoned work, but here we have no way how to propagate the failure
// ObjectDisposedException.ThrowIf(_isDisposed, this);
return;
}

var vt = Queue.Reader.WaitToReadAsync();
if (_isCancellationRequested)
{
return;
}

if (vt.IsCompleted)
{
DataIsAvailable();
Expand Down Expand Up @@ -138,7 +149,7 @@ private static void BackgroundJobHandler()

private void Pump()
{
if (_isDisposed)
if (_isDisposed || _isCancellationRequested)
{
// FIXME: there could be abandoned work, but here we have no way how to propagate the failure
pavelsavara marked this conversation as resolved.
Show resolved Hide resolved
// ObjectDisposedException.ThrowIf(_isDisposed, this);
Expand Down Expand Up @@ -168,7 +179,7 @@ private void Pump()
finally
{
// If an item throws, we want to ensure that the next pump gets scheduled appropriately regardless.
if (!_isDisposed) AwaitNewData();
if (!_isDisposed && !_isCancellationRequested) AwaitNewData();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,9 @@ private static Task<T> RunAsyncImpl<T>(Func<Task<T>> body, CancellationToken can
// continuation should not be running synchronously in the JSWebWorker thread because we are about to kill it after we resolve/reject the Task.
var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
var capturedContext = SynchronizationContext.Current;
var t = new Thread(() =>
var thread = new Thread(() =>
{
CancellationTokenRegistration? reg = null;
try
{
if (cancellationToken.IsCancellationRequested)
Expand All @@ -64,7 +65,17 @@ private static Task<T> RunAsyncImpl<T>(Func<Task<T>> body, CancellationToken can
return;
}

JSHostImplementation.InstallWebWorkerInterop(false);
var synchronizationContext = JSHostImplementation.InstallWebWorkerInterop(false, cancellationToken);

reg = cancellationToken.Register(() =>
pavelsavara marked this conversation as resolved.
Show resolved Hide resolved
{
synchronizationContext.Send(static o =>
{
JSHostImplementation.UninstallWebWorkerInterop();
}, synchronizationContext);
SendWhenException(parentContext, tcs, new OperationCanceledException(cancellationToken));
});

var childScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task<T> res = body();
// This code is exiting thread main() before all promises are resolved.
Expand All @@ -73,16 +84,18 @@ private static Task<T> RunAsyncImpl<T>(Func<Task<T>> body, CancellationToken can
{
SendWhenDone(parentContext, tcs, res);
JSHostImplementation.UninstallWebWorkerInterop();
reg?.Dispose();
}, childScheduler);
}
catch (Exception ex)
{
SendWhenException(parentContext, tcs, ex);
JSHostImplementation.UninstallWebWorkerInterop();
reg?.Dispose();
}

});
JSHostImplementation.SetHasExternalEventLoop(t);
t.Start();
JSHostImplementation.SetHasExternalEventLoop(thread);
thread.Start();
return tcs.Task;
}

Expand All @@ -92,8 +105,9 @@ private static Task RunAsyncImpl(Func<Task> body, CancellationToken cancellation
// continuation should not be running synchronously in the JSWebWorker thread because we are about to kill it after we resolve/reject the Task.
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var capturedContext = SynchronizationContext.Current;
var t = new Thread(() =>
var thread = new Thread(() =>
{
CancellationTokenRegistration? reg = null;
try
{
if (cancellationToken.IsCancellationRequested)
Expand All @@ -102,7 +116,17 @@ private static Task RunAsyncImpl(Func<Task> body, CancellationToken cancellation
return;
}

JSHostImplementation.InstallWebWorkerInterop(false);
var synchronizationContext = JSHostImplementation.InstallWebWorkerInterop(false, cancellationToken);

reg = cancellationToken.Register(() =>
{
synchronizationContext.Send(static o =>
{
JSHostImplementation.UninstallWebWorkerInterop();
}, synchronizationContext);
SendWhenException(parentContext, tcs, new OperationCanceledException(cancellationToken));
});

var childScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task res = body();
// This code is exiting thread main() before all promises are resolved.
Expand All @@ -111,16 +135,19 @@ private static Task RunAsyncImpl(Func<Task> body, CancellationToken cancellation
{
SendWhenDone(parentContext, tcs, res);
JSHostImplementation.UninstallWebWorkerInterop();
reg?.Dispose();
}, childScheduler);
}
catch (Exception ex)
{
SendWhenException(parentContext, tcs, ex);
reg?.Dispose();
JSHostImplementation.UninstallWebWorkerInterop();
}

});
JSHostImplementation.SetHasExternalEventLoop(t);
t.Start();
JSHostImplementation.SetHasExternalEventLoop(thread);
thread.Start();
return tcs.Task;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
<!-- Use following lines to write the generated files to disk. -->
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
<!-- Make debugging easier -->
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
<WasmNativeStrip >false</WasmNativeStrip>
pavelsavara marked this conversation as resolved.
Show resolved Hide resolved
<WasmXHarnessMonoArgs>$(WasmXHarnessMonoArgs) --setenv=XHARNESS_LOG_TEST_START=true</WasmXHarnessMonoArgs>
</PropertyGroup>
<ItemGroup>
<Compile Include="System\Runtime\InteropServices\JavaScript\JavaScriptTestHelper.cs" />
<Compile Include="System\Runtime\InteropServices\JavaScript\JSImportExportTest.cs" />
Expand Down
Loading
Loading