• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 多线程取消TaskPool任务场景
2<!--Kit: ArkTS-->
3<!--Subsystem: CommonLibrary-->
4<!--Owner: @lijiamin2025-->
5<!--Designer: @weng-changcheng-->
6<!--Tester: @kirl75; @zsw_zhushiwei-->
7<!--Adviser: @ge-yafang-->
8
9由于任务池[TaskPool](../reference/apis-arkts/js-apis-taskpool.md)的任务对象[Task](../reference/apis-arkts/js-apis-taskpool.md#task)不支持跨线程传递,无法在子线程中直接取消任务。从 API version 18 开始,Task新增了[任务ID](../reference/apis-arkts/js-apis-taskpool.md#属性)属性,支持通过任务ID在子线程中取消任务。开发者可将已创建任务的任务ID存储在[Sendable对象](./arkts-sendable.md)中,需要取消任务时,通过Sendable对象在子线程中取消任务。详情可参考以下示例。
10
111. 定义一个Sendable类,在类属性中存储任务ID。
12
13   ```ts
14   // sendable.ets
15
16   @Sendable
17   export class SendableTest {
18    // 存储任务ID
19     private taskId: number = 0;
20
21     constructor(id: number) {
22       this.taskId = id;
23     }
24
25     public getTaskId(): number {
26       return this.taskId;
27     }
28   }
29   ```
30
312. 在UI主线程向TaskPool提交一个延时任务,并在子线程取消该任务。
32
33   ```ts
34   // Index.ets
35
36   import { taskpool } from '@kit.ArkTS';
37   import { SendableTest } from './sendable';
38   import { BusinessError } from '@kit.BasicServicesKit';
39
40   @Concurrent
41   function cancel(send: SendableTest) {
42     // 在多线程中通过任务ID取消任务
43     taskpool.cancel(send.getTaskId());
44     console.info("cancel task finished");
45   }
46
47   @Concurrent
48   function delayed() {
49     console.info("delayed task finished");
50   }
51
52   @Entry
53   @Component
54   struct Index {
55     @State message: string = 'Hello World';
56
57     build() {
58       Row() {
59         Column() {
60           Text(this.message)
61             .fontSize(50)
62             .fontWeight(FontWeight.Bold)
63             .onClick(async () => {
64               let task = new taskpool.Task(delayed);
65               taskpool.executeDelayed(2000, task).catch((e: BusinessError) => {
66                 console.error(`taskpool execute error, message is: ${e.message}`); // taskpool execute error, message is: taskpool:: task has been canceled
67               });
68               let send = new SendableTest(task.taskId);
69               taskpool.execute(cancel, send);
70             })
71         }
72         .width('100%')
73       }
74       .height('100%')
75     }
76   }
77   ```