gpt4 book ai didi

ios - 如何从 GCD 调度队列中删除排队的 block ?

转载 作者:技术小花猫 更新时间:2023-10-29 11:13:30 28 4
gpt4 key购买 nike

我正在尝试重新安排将处理更新操作的排队 block 。主要目标是以最少的(UI 更新请求)更新 UI 对象(在线用户表...)。 (服务器有时会大量更新,耶!)

为简单起见,主要场景是;

  • dispatch_queue_t 实例(将处理给定 UI 更新 block 的队列)是一个串行调度队列(私有(private)调度队列)

  • 操作(UI 更新 block )使用 dispatch_after 安排 t 时间(不是针对每个数据集更新进行更新,而是在 t 时间内收集更新请求并为它们执行单个 UI 更新)

  • 如果我们的数据集更新了,请检查是否已经存在预定事件。如果是,从 dispatch_queue_t 实例中取消调度。然后用 t 个时间延迟重新安排相同的 block 。

还有;

t 是用户可能不会注意到的少量时间间隔(如 500 毫秒)。欢迎任何替代方法。

我这样做的动机;

我通过 Android 的处理程序(post 和 removeCallbacks 与 Runnable 实例的组合)应用了相同的逻辑,我希望我可以在 iOS 上实现相同的逻辑。

编辑:

正如@Sven 建议的那样,使用 NSOperationQueue 更适合这种场景,因为它们支持取消每个 NSOperation。我浏览了文档并找到了;

Canceling Operations Once added to an operation queue, an operation object is effectively owned by the queue and cannot be removed. The only way to dequeue an operation is to cancel it. You can cancel a single individual operation object by calling its cancel method or you can cancel all of the operation objects in a queue by calling the cancelAllOperations method of the queue object.

You should cancel operations only when you are sure you no longer need them. Issuing a cancel command puts the operation object into the “canceled” state, which prevents it from ever being run. Because a canceled operation is still considered to be “finished”, objects that are dependent on it receive the appropriate KVO notifications to clear that dependency. Thus, it is more common to cancel all queued operations in response to some significant event, like the application quitting or the user specifically requesting the cancellation, rather than cancel operations selectively.

最佳答案

这也可以使用 GCD 轻松完成,无需在这里伸手去拿 NSOperationQueue 的大锤子。

只需直接使用非重复调度计时器源而不是 dispatch_after(它只是围绕此类计时器源的便利包装器,它实际上不会将 block 排入队列,直到计时器熄灭)。

您可以使用 dispatch_source_set_timer() 重新安排挂起的计时器源执行。

关于ios - 如何从 GCD 调度队列中删除排队的 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15005452/

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