同时调用非可发送非结构化列表中的异步函数

问题描述 投票:0回答:1
class NonSendable {
    var name: String = ""

    func doSomething() async {}
}

let listOfNonSendable = [NonSendable]()

我有一个

NonSendable
列表,我想为
func doSomething() async {}
列表中的所有
NonSendable
致电
Task

for ns in listOfNonSendable {
    Task {
        await ns.doSomething()
    }
}

但是它显示

Value of non-Sendable type '@isolated(any) @async @callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <()>' accessed after being transferred; later accesses could race

如何解决该错误或者最好的方法是什么?

swift concurrency
1个回答
0
投票

如果你确定这里不会出现竞争条件或任何并发问题,你可以使用@unchecked

class NonSendable: @unchecked Sendable {

如果没有,你可以将类转换为actor,或者使用dispatchQueue创建锁

private let queue = DispatchQueue(label: "Your label", attributes: .concurrent)
func doSomething() async {
    // Use `lockQueue` to serialize access.
    await withCheckedContinuation { continuation in
        queue.async {
            // Perform the operation in the queue
            print("Doing something in \(self.name)")
            
            // Resume the async continuation after finishing
            continuation.resume()
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.