在swift中限制dispatch_queue_create中的任务数量

时间:2016-06-03 21:36:08

标签: swift

我想限制在dispatch_queue_t中运行的任务数量,如果达到限制则忽略所有任务,如何以快速语言实现这一点,我找不到任何有关它的信息?

1 个答案:

答案 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()