Skip to content

Commit

Permalink
Replace TaskCompletionSource with ManualResetEventSlim
Browse files Browse the repository at this point in the history
  • Loading branch information
Trung Tran committed Jun 9, 2024
1 parent 730ca83 commit 6d02edc
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 12 deletions.
11 changes: 2 additions & 9 deletions Jint/JsValueExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -650,16 +650,9 @@ public static JsValue UnwrapIfPromise(this JsValue value)
if (value is JsPromise promise)
{
var engine = promise.Engine;
var task = promise.TaskCompletionSource.Task;
var completedEvent = promise.CompletedEvent;
engine.RunAvailableContinuations();
engine.AddToEventLoop(() =>
{
if (!task.IsCompleted)
{
// Task.Wait has the potential of inlining the task's execution on the current thread; avoid this.
((IAsyncResult) task).AsyncWaitHandle.WaitOne();
}
});
engine.AddToEventLoop(completedEvent.Wait);
engine.RunAvailableContinuations();
switch (promise.State)
{
Expand Down
7 changes: 4 additions & 3 deletions Jint/Native/JsPromise.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Threading;
using Jint.Native.Object;
using Jint.Native.Promise;
using Jint.Runtime;
Expand All @@ -12,7 +13,7 @@ internal sealed class JsPromise : ObjectInstance

// valid only in settled state (Fulfilled or Rejected)
internal JsValue Value { get; private set; } = null!;
internal TaskCompletionSource<JsPromise> TaskCompletionSource { get; }= new();
internal ManualResetEventSlim CompletedEvent { get; } = new();

internal List<PromiseReaction> PromiseRejectReactions = new();
internal List<PromiseReaction> PromiseFulfillReactions = new();
Expand Down Expand Up @@ -127,7 +128,7 @@ private JsValue RejectPromise(JsValue reason)
var reactions = PromiseRejectReactions;
PromiseRejectReactions = new List<PromiseReaction>();
PromiseFulfillReactions.Clear();
TaskCompletionSource.SetCanceled();
CompletedEvent.Set();

// Note that this part is skipped because there is no tracking yet
// 7. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "reject").
Expand All @@ -147,7 +148,7 @@ private JsValue FulfillPromise(JsValue result)
var reactions = PromiseFulfillReactions;
PromiseFulfillReactions = new List<PromiseReaction>();
PromiseRejectReactions.Clear();
TaskCompletionSource.SetResult(this);
CompletedEvent.Set();

return PromiseOperations.TriggerPromiseReactions(_engine, reactions, result);
}
Expand Down

0 comments on commit 6d02edc

Please sign in to comment.