无法设置 AsyncStream `onTermination` 处理程序

Can't set AsyncStream `onTermination` handler

有没有人成功创建 AsyncStream 并设置其 onTermination 处理程序?我做不到。以下是直接从提案 (https://github.com/apple/swift-evolution/blob/main/proposals/0314-async-stream.md) 复制粘贴的,除了我通过将 detach 现代化为 Task.detached 来消除警告之外:

    let t = Task.detached {
      func make123Stream() -> AsyncStream<Int> {
        AsyncStream { continuation in
          continuation.onTermination = { termination in
            switch termination {
            case .finished:
                print("Regular finish")
            case .cancelled:
                print("Cancellation")
            }
          }
            Task.detached {
            for n in 1...3 {
              continuation.yield(n)
              sleep(2)
            }
            continuation.finish()
          }
        }
      }

      for await n in make123Stream() {
        print("for-in: \(n)")
      }
      print("After")
    }
    sleep(3)
    t.cancel()

看起来不错,但无法编译,而且我找不到编译它的方法。 onTermination setter 上的错误消息显示为:

 Converting non-concurrent function value to 
 '@Sendable (AsyncStream<Int>.Continuation.Termination) -> Void' 
 may introduce data races

我不知道编译器要我做什么。有没有人解决过这个问题,解决方案是什么?

(我已经提交了一个错误。)

更新:

您可以通过添加 @Sendable 作为闭包内的第一件事(在捕获列表、参数和 in 关键字之前)来解决此错误,例如:

continuation.onTermination = { @Sendable termination in
    switch termination {
    case .finished:
        print("Regular finish")
    case .cancelled:
        print("Cancellation")
    @unknown default:
        break
    }
}

原回答:

是的,我猜这是一个错误,因为我能够通过添加以下内容来编译它:

as (@Sendable (AsyncStream<Int>.Continuation.Termination) -> Void)

关闭后,喜欢:

continuation.onTermination = { termination in
    switch termination {
    case .finished:
        print("Regular finish")
    case .cancelled:
        print("Cancellation")
    @unknown default:
        break
    }
} as (@Sendable (AsyncStream<Int>.Continuation.Termination) -> Void)

(我还添加了 @unknown default 案例以消除出现的新警告。)