我想限制在dispatch_queue_t
中运行的任务数量,如果达到限制则忽略所有任务,如何以快速语言实现这一点,我找不到任何有关它的信息?
答案 0 :(得分:0)
Apple已经在NSOperationQueue
为您完成了大部分工作。您只需稍微修改它以满足您的需求:
class MyOperationQueue: NSOperationQueue {
override func addOperationWithBlock(block: () -> Void) {
if self.operationCount < self.maxConcurrentOperationCount {
super.addOperationWithBlock(block)
}
}
}
let queue = MyOperationQueue()
queue.maxConcurrentOperationCount = 2
queue.addOperationWithBlock {
print("Task 1")
sleep(5)
}
queue.addOperationWithBlock {
print("Task 2")
sleep(5)
}
queue.addOperationWithBlock {
// This will be ignored
print("Task 3")
sleep(5)
}
queue.waitUntilAllOperationsAreFinished()