#鸿蒙通关秘籍#在鸿蒙HarmonyOS NEXT中如何利用Taskpool实现顺序执行任务?

HarmonyOS
7天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
墨舞涯EVT

在HarmonyOS NEXT中,可以通过业务逻辑判断或利用任务依赖关系,实现顺序执行任务,以下展示了两种方法的示例代码:

  1. 利用业务逻辑判断来执行顺序任务:
@Concurrent

function ServiceHandle1(pars: number): number {
  hilog.info(0x0000, 'testTag', 'start ServiceHandle1:%{public}d', pars);
  let result = 0;
  return result;
}

@Concurrent

function ServiceHandle2(pars: number): number {
  hilog.info(0x0000, 'testTag', 'start ServiceHandle2:%{public}d', pars);
  let result = 1;
  return result;
}

export function SyncHandle() {
  let task1: taskpool.Task = new taskpool.Task(ServiceHandle1, 1);
  hilog.info(0x0000, 'testTag', 'sync handle');
  taskpool.execute(task1, taskpool.Priority.HIGH).then((res1: object) => {
    hilog.info(0x0000, 'testTag', 'ServiceHandle result :%{public}d', res1);
    if (g_callback != null) {
      g_callback('task1 finish.');
    }
    if ((res1 as Number) == 0) {
      let task2: taskpool.Task = new taskpool.Task(ServiceHandle2, 2);
      taskpool.execute(task2, taskpool.Priority.HIGH).then((res2: object) => {
        hilog.info(0x0000, 'testTag', 'ServiceHandle2 result :%{public}d', res2);
        if (g_callback != null) {
          g_callback('task2 finish.');
        }
      });
    }
  });
}
  1. 利用任务依赖关系或SequenceRunner来执行顺序任务:
@Concurrent

function DependencyHandle(args: number): number {
  let t: number = Date.now();
  while ((Date.now() - t) < 1000) {
    continue;
  }
  return args;
}

export function AddDependencyTest() {
  let task1:taskpool.Task = new taskpool.Task(DependencyHandle, 100);
  let task2:taskpool.Task = new taskpool.Task(DependencyHandle, 200);
  let task3:taskpool.Task = new taskpool.Task(DependencyHandle, 300);

  hilog.info(0x0000, 'testTag', 'dependency: add dependency start');
  task1.addDependency(task2);
  task2.addDependency(task3);
  hilog.info(0x0000, 'testTag', 'dependency: add dependency end');

  hilog.info(0x0000, 'testTag', 'dependency: start execute second');
  taskpool.execute(task1).then(() => {
    hilog.info(0x0000, 'testTag', 'dependency: first task1 success');
    if (g_callback != null) {
      g_callback('task1 finish.');
    }
  })
  taskpool.execute(task2).then(() => {
    hilog.info(0x0000, 'testTag', 'dependency: second task2 success');
    if (g_callback != null) {
      g_callback('task2 finish.');
    }
  })
  taskpool.execute(task3).then(() => {
    hilog.info(0x0000, 'testTag', 'dependency: third task3 success');
    if (g_callback != null) {
      g_callback('task3 finish.');
    }
  })
}

通过任务依赖管理,可以确保任务按预设的顺序进行,task1依赖task2,task2依赖task3,任务执行的顺序将保障按照依赖关系从后到前执行。

分享
微博
QQ
微信
回复
7天前
相关问题
如何利用taskpool执行任务
2034浏览 • 1回复 待解决
HarmonyOS 怎么实现任务串行顺序执行
342浏览 • 1回复 待解决
HarmonyOS线程池周期执行任务
1040浏览 • 1回复 待解决
如何获知TaskPool执行顺序、优先级?
799浏览 • 0回复 待解决