gpt4 book ai didi

ios - swift +异步: How to execute a callback on the same thread where it was created?

转载 作者:行者123 更新时间:2023-11-29 00:53:35 25 4
gpt4 key购买 nike

使用Async库中,在后台线程上工作的简单模式可能如下所示:

// Assume we start on the main thread

let onResultComplete: (result: ResultType) -> Void = { result in
Async.main {
// Code to handle one result at a time on the main thread
}
}

Async.background {
doCalculationsThatProduceManyResults(onEachResultComplete: onResultComplete)
}

现在考虑这种情况,其中代码已经在后台线程上执行:

// Assume we start on some "unknown background thread"

let onResultComplete: (result: ResultType) -> Void = { result in
Async.??? {
// Code to handle one result at a time on the "unknown background thread"
}
}

Async.background {
doCalculationsThatProduceManyResults(onEachResultComplete: onResultComplete)
}

如何强制关闭onResultComplete在我调用 Async.background相同 未知后台线程上运行?

我愿意接受任何使用 GCD 方法的建议。

最佳答案

在 iOS 或 macOS 上,如果某些代码在未知线程或调度队列(例如:“执行上下文”)上执行,则无法可靠地为它获取一些“句柄”——好吧,除非这是主线程。

因此,您的问题的解决方案是首先创建或获取一个已知 执行上下文(又名调度队列或线程)并在此处执行您的代码。然后,在延续(又名完成处理程序)中,再次显式分派(dispatch)回同一执行上下文并继续您的代码。

关于ios - swift +异步: How to execute a callback on the same thread where it was created?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37847983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com