文档管理中心

多线程取消TaskPool任务场景

由于任务池TaskPool的任务对象Task不支持跨线程传递,无法在子线程中直接取消任务。从API version 18开始,Task新增了任务ID属性,支持通过任务ID在子线程中取消任务。开发者可将已创建任务的任务ID存储在Sendable对象中,需要取消任务时,通过Sendable对象在子线程中取消任务。详情可参考以下示例。

  1. 定义一个Sendable类,在类属性中存储任务ID。

    收起
    自动换行
    深色代码主题
    复制
    1. // sendable.ets
    2. @Sendable
    3. export class SendableTest {
    4. // 存储任务ID
    5. private taskId: number = 0;
    6. constructor(id: number) {
    7. this.taskId = id;
    8. }
    9. public getTaskId(): number {
    10. return this.taskId;
    11. }
    12. }
  2. 在UI主线程向TaskPool提交一个延时任务,并在子线程取消该任务。

    收起
    自动换行
    深色代码主题
    复制
    1. // TaskpoolCancel.ets
    2. import { taskpool } from '@kit.ArkTS';
    3. import { SendableTest } from '../utils/Sendable';
    4. import { BusinessError } from '@kit.BasicServicesKit';
    5. import { PromptAction } from '@kit.ArkUI';
    6. @Concurrent
    7. function cancel(send: SendableTest) {
    8. // 在子线程中通过任务ID取消任务
    9. taskpool.cancel(send.getTaskId());
    10. console.info('cancel task finished');
    11. }
    12. @Concurrent
    13. function delayed() {
    14. console.info('delayed task finished');
    15. }
    16. @Entry
    17. @Component
    18. struct TaskpoolCancel {
    19. @State message: string = 'CancelTaskpool';
    20. @State returnMessage: string = 'return...';
    21. @State promptAction: PromptAction = this.getUIContext().getPromptAction();
    22. build() {
    23. Row() {
    24. Column() {
    25. Button(this.message)
    26. .fontSize(25)
    27. .fontWeight(FontWeight.Bold)
    28. .onClick(async () => {
    29. let task = new taskpool.Task(delayed);
    30. taskpool.executeDelayed(2000, task).catch((e: BusinessError) => {
    31. console.error(`taskpool execute error, message is: ${e.message}`);
    32. // taskpool execute error, message is: taskpool:: task has been canceled.
    33. });
    34. let send = new SendableTest(task.taskId);
    35. taskpool.execute(cancel, send).then(() => {
    36. this.returnMessage = 'Taskpool canceled!';
    37. this.promptAction.showToast({ message: this.returnMessage });
    38. });
    39. })
    40. // ...
    41. }
    42. .width('100%')
    43. }
    44. .height('100%')
    45. }
    46. }
在 指南 中进行搜索
请输入您想要搜索的关键词