diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 40d22d337553cb..9882a504482ee9 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -1861,6 +1861,21 @@ Calling `unref()` on a worker allows the thread to exit if this is the only active handle in the event system. If the worker is already `unref()`ed calling `unref()` again has no effect. +### `worker[Symbol.asyncDispose]()` + + + +Calls [`worker.terminate()`][] when the dispose scope is exited. + +```js +async function example() { + await using worker = new Worker('for (;;) {}', { eval: true }); + // Worker is automatically terminate when the scope is exited. +} +``` + ## Notes ### Synchronous blocking of stdio diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 8b43dcac320777..9b6cd7c1cf1d11 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -19,6 +19,7 @@ const { String, StringPrototypeTrim, Symbol, + SymbolAsyncDispose, SymbolFor, TypedArrayPrototypeFill, Uint32Array, @@ -407,6 +408,10 @@ class Worker extends EventEmitter { }); } + async [SymbolAsyncDispose]() { + await this.terminate(); + } + ref() { if (this[kHandle] === null) return; diff --git a/test/parallel/test-worker-dispose.mjs b/test/parallel/test-worker-dispose.mjs new file mode 100644 index 00000000000000..5d4e95428566f9 --- /dev/null +++ b/test/parallel/test-worker-dispose.mjs @@ -0,0 +1,10 @@ +import * as common from '../common/index.mjs'; +import { Worker } from 'node:worker_threads'; + +let w; +{ + // Verifies that the worker is async disposable + await using worker = new Worker('for(;;) {}', { eval: true }); + w = worker; + w.on('exit', common.mustCall()); +}