harmony 鸿蒙Canceling Tasks in Multithreading with TaskPool

  • 2025-06-06
  • 浏览 (4)

Canceling Tasks in Multithreading with TaskPool

Task objects of the TaskPool cannot be passed to child threads. Therefore, tasks cannot be canceled from child threads prior to API version 18. Starting from API version 18, tasks have been enhanced with the task ID, allowing tasks to be canceled in child threads using this ID. The following example describes how to cancel a task that has been submitted to the TaskPool in a multithreaded environment. You can store the task ID of a created task in a Sendable object and use this object to cancel the task from a child thread.

  1. Define a Sendable class and store the task ID in the class properties.
   // Mock.ets

   @Sendable
   export class SendableTest {
    // Store the task ID.
     private taskId: number = 0;

     constructor(id: number) {
       this.taskId = id;
     }

     public getTaskId(): number {
       return this.taskId;
     }
   }
  1. Submit a delayed task to the TaskPool from the UI main thread and cancel it from a child thread.
   // Index.ets

   import { taskpool } from '@kit.ArkTS';
   import { SendableTest } from './Mock'

   @Concurrent
   function cancel(send: SendableTest) {
     console.info("cancel task finished");
     // Cancel the task in the child thread based on the task ID.
     taskpool.cancel(send.getTaskId());
   }

   @Concurrent
   function delayed() {
     console.info("delayed task finished");
   }

   @Entry
   @Component
   struct Index {
     @State message: string = 'Hello World!';
     @State books: string[] = [];

     build() {
       Column({ space: 1 }) {
         Button(this.books[3])
           .fontSize(20)
           .padding(10)
           .fontWeight(FontWeight.Bold)
           .onClick(async () => {
             let task = new taskpool.Task(delayed);
             taskpool.executeDelayed(2000, task);
             let send = new SendableTest(task.taskId);
             taskpool.execute(cancel, send);
           })
       }
       .height('100%')
       .width('100%')
     }
   }

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArkTS

harmony 鸿蒙Configuring arkOptions in build-profile.json5

harmony 鸿蒙Asynchronous Lock

harmony 鸿蒙Ark Bytecode File Format

harmony 鸿蒙Naming Conventions for Ark Bytecode Functions

harmony 鸿蒙Ark Bytecode Fundamentals

harmony 鸿蒙Overview of Ark Bytecode

harmony 鸿蒙Shared Container

harmony 鸿蒙Asynchronous Waiting

harmony 鸿蒙ArkTS Cross-Language Interaction

0  赞