【发布时间】:2012-11-25 14:11:18
【问题描述】:
我正在尝试实现一个操作队列,我有以下场景:
NSOperation A
NSOperation B
NSOperation C
NSOperation D
NSOperationQueue queue
我开始将A 添加到queue。
在执行A 期间,我需要从B 获取一些数据,并且在B 返回我需要的内容之前,我无法继续使用A。
B 取决于C 和C 取决于D 会发生同样的情况。
为了管理这个,在每个NSOperation我都有这个代码:
NSOperation *operation; //This can be A, B, C, D or any other NSOperation
[self setQueuePriority:NSOperationQueuePriorityVeryLow]; //Set the current NSOperation with low priority
[queue addOperation: operation]; //Add the operation that I want to the queue
while(!operation.isFinished && !self.isCancelled){} //I need to wait the operation that I depend before moving on with the current operation
[self setQueuePriority:NSOperationQueuePriorityNormal]; //After the while, the other operation finished so I return my priority to normal and continue
if(self.isCancelled){ //If I get out of the while because the current operation was cancelled I also cancel the other operation.
[operation cancel];
}
我的问题是,当我有 3 或 4 个 NSOperations 等待并执行 while(!operacao.isFinished && !self.isCancelled){} 时,我的代码会冻结,因为对我很重要的 NSOperation 不会被执行,即使它具有更高的优先级。
我尝试了什么
在执行期间添加依赖,但由于我的 NSOperation 已经在运行,我似乎没有任何效果。
我可以做一些事情
[operation start],而不是将操作添加到队列中。可以,但是取消当前操作也会取消我开始的其他操作?我可以做类似
while(!operacao.isFinished && !self.isCancelled){[NSThread sleepForTimeInterval:0.001];}的事情。它有效,但这是正确的方法吗?也许有更好的解决方案。
在这种情况下,我如何保证我想要的操作将运行而其他操作将在后台等待?解决这个问题的正确方法是什么?
如果有人问我为什么在开始队列之前不添加依赖项,因为只有在某些条件为真时,操作才需要另一个操作。只有在执行期间我才会知道我是否需要其他操作。
感谢您的宝贵时间。
【问题讨论】:
标签: objective-c ios nsthread nsoperation nsoperationqueue