• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Canceling Tasks in Multithreading with TaskPool
2
3[Task](../reference/apis-arkts/js-apis-taskpool.md#task) objects of the [TaskPool](../reference/apis-arkts/js-apis-taskpool.md) cannot be passed across threads. Therefore, tasks cannot be canceled from child threads. Starting from API version 18, tasks have been enhanced with the [task ID](../reference/apis-arkts/js-apis-taskpool.md#properties), 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](./arkts-sendable.md) and use this object to cancel the task from a child thread.
4
51. Define a Sendable class and store the task ID in the class properties.
6
7   ```ts
8   // Mock.ets
9
10   @Sendable
11   export class SendableTest {
12    // Store the task ID.
13     private taskId: number = 0;
14
15     constructor(id: number) {
16       this.taskId = id;
17     }
18
19     public getTaskId(): number {
20       return this.taskId;
21     }
22   }
23   ```
24
252. Submit a delayed task to the TaskPool from the UI main thread and cancel it from a child thread.
26
27   ```ts
28   // Index.ets
29
30   import { taskpool } from '@kit.ArkTS';
31   import { SendableTest } from './Mock'
32
33   @Concurrent
34   function cancel(send: SendableTest) {
35     console.info("cancel task finished");
36     // Cancel the task in the child thread based on the task ID.
37     taskpool.cancel(send.getTaskId());
38   }
39
40   @Concurrent
41   function delayed() {
42     console.info("delayed task finished");
43   }
44
45   @Entry
46   @Component
47   struct Index {
48     @State message: string = 'Hello World!';
49     @State books: string[] = [];
50
51     build() {
52       Column({ space: 1 }) {
53         Button(this.books[3])
54           .fontSize(20)
55           .padding(10)
56           .fontWeight(FontWeight.Bold)
57           .onClick(async () => {
58             let task = new taskpool.Task(delayed);
59             taskpool.executeDelayed(2000, task).catch((e: BusinessError) => {
60               console.error(`taskpool execute error, message is: ${e.message}`); // taskpool execute error, message is: taskpool:: task has been canceled
61             });
62             let send = new SendableTest(task.taskId);
63             taskpool.execute(cancel, send);
64           })
65       }
66       .height('100%')
67       .width('100%')
68     }
69   }
70   ```
71