gpt4 book ai didi

swift - 如何快速终止调度队列的异步执行?

转载 作者:行者123 更新时间:2023-11-28 12:08:44 25 4
gpt4 key购买 nike

我目前正在使用 Particle 的 API 进行事件流式处理,我希望在某个未知的时间点终止事件订阅(我知道有一个用于定时终止的接口(interface))。

ParticleCloud.sharedInstance().subscribeToAllEvents(withPrefix: prefix, handler: { (eventOpt :ParticleEvent?, error : Error?) in
if let _ = error {
eprint (message: "Could not subscribe to events")
} else {
let serialQueue = DispatchQueue(label: "foo")
serialQueue.async(execute: {
...
})
}
})

据我所知,swift 中的 DispatchQueue 对象从池中获取空闲线程并运行我省略的函数(因为它与问题无关)。我想要一些方法来稍后结束 .async 调用,因为它现在无限期地运行。

我查看了堆栈溢出以寻找稍后暂停或恢复调度队列的可能性,例如:

ParticleCloud.sharedInstance().subscribeToAllEvents(withPrefix: prefix, handler: { (eventOpt :ParticleEvent?, error : Error?) in
if let _ = error {
eprint (message: "Could not subscribe to events")
} else {
let serialQueue = DispatchQueue(label: "foo")
serialQueue.async(execute: {
...
})
serialQueue.suspend() // EXC_BAD_INSTRUCTION
}
})

但它导致了 EXC_BAD_INSTRUCTION。诊断(无对象等)没有帮助。

不幸的是,我不知道如何给出这个问题的 MVCE 示例,因为它需要粒子硬件和 particle.io 上的注册帐户,所以我为此道歉。

subscribeToAllEvents 的 API 在这里:https://docs.particle.io/reference/ios/#events-sub-system

最佳答案

引用 subscribeToAllEventsWithPrefix:handler: 的文档:

Returns: eventListenerID function will return an id type object as the eventListener registration unique ID - keep and pass this object to the unsubscribe method in order to remove this event listener

虽然写的很乱,但大意是订阅函数返回一个对象。您应该将对象保存在实例属性中。当您准备好取消订阅时,将对象传递给取消订阅函数。

所以:

// Instance property.
var subscription: Any?

subscription = ParticleCloud.sharedInstance().subscribeToAllEvents(withPrefix: prefix, handler: { ... })

// When it's time to unsubscribe...
if let subscription = subscription {
ParticleCloud.sharedInstance().unsubscribeFromEvent(withID: subscription)
self.subscription = nil
}

关于swift - 如何快速终止调度队列的异步执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48956274/

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