Skip to content

Commit ce91a94

Browse files
committed
fix: drain runtime microtasks from run loop
1 parent 916b455 commit ce91a94

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

NativeScript/runtime/Runtime.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,20 @@ Runtime::Runtime() {
109109
currentRuntime_ = this;
110110
workerId_ = -1;
111111
runtimeLoop_ = nullptr;
112+
microtaskObserver_ = nullptr;
112113
// workerCache_ = Caches::Workers;
113114
}
114115

115116
Runtime::~Runtime() {
116117
currentRuntime_ = nullptr;
118+
if (microtaskObserver_ != nullptr) {
119+
if (runtimeLoop_ != nullptr) {
120+
CFRunLoopRemoveObserver(runtimeLoop_, microtaskObserver_,
121+
kCFRunLoopCommonModes);
122+
}
123+
CFRelease(microtaskObserver_);
124+
microtaskObserver_ = nullptr;
125+
}
117126
if (runtimeLoop_ != nullptr) {
118127
unregisterRuntimePromiseRunLoop(runtimeLoop_);
119128
runtimeLoop_ = nullptr;
@@ -330,6 +339,24 @@ void Runtime::Init(bool isWorker) {
330339
js_create_napi_env(&env_, runtime_);
331340

332341
runtimeLoop_ = CFRunLoopGetCurrent();
342+
{
343+
Runtime* runtime = this;
344+
microtaskObserver_ = CFRunLoopObserverCreateWithHandler(
345+
kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 0,
346+
^(CFRunLoopObserverRef, CFRunLoopActivity) {
347+
napi_env env = runtime->env_;
348+
if (env == nullptr || !Runtime::IsAlive(env)) {
349+
return;
350+
}
351+
352+
NapiScope scope(env);
353+
js_execute_pending_jobs(env);
354+
});
355+
if (microtaskObserver_ != nullptr) {
356+
CFRunLoopAddObserver(runtimeLoop_, microtaskObserver_,
357+
kCFRunLoopCommonModes);
358+
}
359+
}
333360

334361
{
335362
SpinLock lock(envsMutex_);

NativeScript/runtime/Runtime.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ class Runtime {
5656
private:
5757
int workerId_;
5858
CFRunLoopRef runtimeLoop_;
59+
CFRunLoopObserverRef microtaskObserver_;
5960
double startTime_;
6061
double realtimeOrigin_;
6162

0 commit comments

Comments
 (0)