Swift 任务依赖处理

问题描述 投票:0回答:1

我有 2 个异步任务。并且一个任务根据其他任务的条件以嵌套方式运行。我想实现类似下面代码的效果。 Task1 和 Task2 都有 AsyncStreams 在流中返回多个值。根据这些值,我启动 Task2。 请问有什么建议吗?

Task1 {
  /// AsyncStream1
  for try await result1 in stream1 {
    if result1 == A {
      Task2 {
        /// AsyncStream2
        for try await result2 in stream2 {
          if result2 == X {
            /// Stop Task2 if Task1 has completed (Stream1 has finished)
            /// THIS IS WHAT I WANT TO ACHIEVE
          }
        }
      }
    }
    if result1 == B {
      /// Stop Task1 if Task2 has completed (Stream2 has finished)
      /// THIS IS WHAT I WANT TO ACHIEVE
    }
  }
}

只会创建一个

Task2
。用例是这样的:
result1 == A
最多只能接收一次,并且可能只收到一个
Task2
。假设如果案件达到
result1 == B
Task2
就已经开始了。

swift async-await concurrency task
1个回答
0
投票

您只需在

for await
循环结束时将标志设置为 true 即可。为了安全地执行此操作,请将标志隔离到参与者。

假设任务不会被取消,

actor SomeActor {
    var task1Finished = false
    var task2Finished = false
    
    func startTask1() async throws {
        for try await result1 in stream1 {
            if result1 == A {
                Task {
                    try await startTask2()
                }
            }
            if result1 == B, task2Finished {
                break
            }
        }
        task1Finished = true
    }
    
    func startTask2() async throws {
        for try await result2 in stream2 {
            if result2 == X, task1Finished {
                break
            }
        }
        task2Finished = true
    }
}

如果需要处理取消,请检查循环中的

Task.isCancelled
并适当设置标志。

© www.soinside.com 2019 - 2024. All rights reserved.