@@ -109,11 +109,20 @@ Runtime::Runtime() {
109109 currentRuntime_ = this ;
110110 workerId_ = -1 ;
111111 runtimeLoop_ = nullptr ;
112+ microtaskObserver_ = nullptr ;
112113 // workerCache_ = Caches::Workers;
113114}
114115
115116Runtime::~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_);
0 commit comments