Implementing Persistent Worker Threads in HarmonyOS

In HarmonyOS, while TaskPool is ideal for short-lived, independent tasks, scenarios requiring long-lived state or persistent object handles often necessitate the use of Worker threads. Unlike TaskPool, which manages task lifecycles automatically, Worker allows for maintaining a single, consistent execution context.

Creating and Managing a Worker Thread

The implementasion involves the main thread initializing the worker and establishing communication protocols. The worker thread then hendles these messages sequentially against a persistent object instance.

Main Thread Logic

The main thread initializes the worker file, sets up event listeners for responses, and dispatches requests. It is responsible for terminating the worker thread once its lifecycle needs to be concluded.

import worker from '@ohos.worker';

@Entry
@Component
struct MainView {
  @State displayMessage: string = 'Initialized';

  build() {
    Row() {
      Column() {
        Text(this.displayMessage)
          .onClick(() => {
            const persistentWorker = new worker.ThreadWorker('entry/ets/workers/ProcessWorker.ts');
            
            persistentWorker.onmessage = (event): void => {
              this.displayMessage = event.data as string;
            };

            persistentWorker.onerror = (err): void => {
              console.error('Worker Error:', err.message);
            };

            // Dispatching instructions
            persistentWorker.postMessage({ command: 'STORE', payload: 'example_data' });
            persistentWorker.postMessage({ command: 'RETRIEVE' });
            
            // Terminate when operations are complete
            // persistentWorker.terminate();
          })
      }
    }
  }
}

Worker Thread Logic

The worker script initializes a local state holder (the 'handle') that persists across multiple incoming messages. This allows for stateful operations that would otherwise be lost in stateless task distribtuion.

// WorkerState.ts
export class WorkerState {
  private storage: string = '';

  public updateState(value: string): void {
    this.storage = value;
  }

  public fetchState(): string {
    return this.storage;
  }
}

// ProcessWorker.ts
import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker';
import { WorkerState } from './WorkerState';

const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
const stateController = new WorkerState();

workerPort.onmessage = (event: MessageEvents): void => {
  const { command, payload } = event.data;

  switch (command) {
    case 'STORE':
      stateController.updateState(payload);
      workerPort.postMessage('Value cached successfully');
      break;
    case 'RETRIEVE':
      const result = stateController.fetchState();
      workerPort.postMessage(`Current stored value: ${result}`);
      break;
    default:
      console.warn('Unknown command received');
  }
};

By encapsulating logic within a persistent WorkerState instance inside the worker script, developers can perform complex, state-dependent operations without the overhead of re-initializing objects for every function call. Always ensure terminate() is called appropriately to prevent memory leaks in the application.

Tags: HarmonyOS ArkTS Worker multithreading MobileDevelopment

Posted on Mon, 13 Jul 2026 16:51:23 +0000 by Merdok