Read the original article:Using Worker for Multithreaded Concurrency in ArkTS
Requirement Description
The Worker class in ArkTS enables creation of background threads with independent execution contexts. These threads operate outside the UI main thread and are ideal for handling long-running or computationally intensive tasks without freezing the UI.
Background Knowledge
Unlike TaskPool, which handles thread lifecycle automatically, the Worker model grants you full control over the lifecycle of a thread. Each Worker runs in its own context, allowing for data isolation, flexible communication, and customizable initialization.
Worker-based concurrency supports:
- Independent message event loop
- Separate memory context
- Custom termination and control
Implementation Steps
Create a new Worker thread using
new Worker(path), wherepathpoints to an.etsfile containingworkerMain.Use
postMessage()to send data from main thread to the worker.Use
onmessageto receive messages in both main and worker threads.Use
terminate()to stop the worker manually.
Note: Worker must be created in an .ets file. The target file must define a global function named workerMain().
Code Snippet / Configuration
main.ets
import worker from '@ohos.worker';
@Entry
@Component
struct Index {
private myWorker: worker.Worker | undefined = undefined;
aboutToAppear() {
this.myWorker = new worker.Worker('worker.ts');
this.myWorker.onmessage = (data: worker.MessageEvent) => {
console.info('Main thread received message: ' + data.data);
}
this.myWorker.postMessage('Hello from Main Thread');
}
aboutToDisappear() {
this.myWorker?.terminate();
}
build() {
Column() {
Text('Main UI Thread')
}
}
}
worker.ets
import worker from '@ohos.worker';
globalThis.workerMain = function () {
worker.onmessage = function (event: worker.MessageEvent) {
console.info('Worker received: ' + event.data);
worker.postMessage('Hello from Worker');
}
}
Test Results
- Successfully sent and received messages between main thread and worker.
- Verified that
onmessageevent handlers work bidirectionally. - Observed that UI remains responsive while background thread operates independently.
Limitations or Considerations
- Worker file must be separate
.etsfile and containglobalThis.workerMaindefinition. - UI-related operations (e.g. AppStorage, UI rendering) are not accessible in Worker threads.
- Worker threads require manual termination using
terminate(); they do not auto-scale. - Data passed between threads must be serializable (no complex or cyclic structures).
Related Documents
Worker-Multithreaded Concurrency-ArkTS Concurrency-ArkTS-Application Framework - HUAWEI Developers
Top comments (0)