简体   繁体   English

Swift:将操作添加到 DispatchQueue/OperationQueue 但稍后启动队列

[英]Swift: Add operations to DispatchQueue/OperationQueue but launch the queue later

I have data packets coming in but in rare occurrences, the object to handle them isn't ready yet.我有数据包进来,但在极少数情况下,处理它们的对象还没有准备好。 What I'm doing at the moment is我现在正在做的是

  • adding the data to an array将数据添加到数组
  • have a while (true) loop checking for the objects state有一个while (true)循环检查对象状态
  • if the object is ready, pop the array members onto the object如果对象准备好,将数组成员弹出到对象上

This works but it's pretty ugly.这有效,但它非常丑陋。 What I was thinking was to add the pending operations to an OperationQueue and then launch the process once the handling object is ready.我在想的是将挂起的操作添加到 OperationQueue 中,然后在处理对象准备好后启动进程。

However, I cannot find any feature that allows me to have the operations "on hold" until I tell them to start going.但是,在我告诉他们开始之前,我找不到任何允许我“暂停”操作的功能。

What can I do about that?我该怎么办?

you can use NSOperationQueue's isSuspended property.您可以使用 NSOperationQueue 的isSuspended属性。

var isSuspended: Bool { get set }

From Apple's doc:来自苹果的文档:

When the value of this property is false, the queue actively starts operations that are in the queue and ready to execute.当此属性的值为 false 时,队列会主动启动队列中准备执行的操作。 Setting this property to true prevents the queue from starting any queued operations, but already executing operations continue to execute.将此属性设置为 true 可防止队列启动任何排队操作,但已执行的操作会继续执行。 You may continue to add operations to a queue that is suspended but those operations are not scheduled for execution until you change this property to false.您可以继续向挂起的队列添加操作,但在您将此属性更改为 false 之前,不会安排执行这些操作。

Please note that setting this property to true only prevents the operations which haven't started yet.请注意,将此属性设置为 true 只会阻止尚未启动的操作。 In your case, you should set this property to true after you initialize a NSOperationQueue object.在您的情况下,您应该在初始化 NSOperationQueue 对象后将此属性设置为 true。 Once it's ready, set isSuspended to false.准备就绪后,将isSuspended设置为 false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM