Wait for all Operations in queue to finish before performing task

前端 未结 6 1884
小鲜肉
小鲜肉 2021-01-02 07:29

I have an Operation subclass and Operation queue with maxConcurrentOperationCount = 1.

This performs my operations in a sequential order that i add them which is goo

6条回答
  •  粉色の甜心
    2021-01-02 07:55

    My solution is similar to that of https://stackoverflow.com/a/42496559/452115, but I don't add the completionOperation in the main OperationQueue but into the queue itself. This works for me:

    var a = [Int](repeating: 0, count: 10)
    
    let queue = OperationQueue()
    
    let completionOperation = BlockOperation {
        print(a)
    }
    
    queue.maxConcurrentOperationCount = 2
    for i in 0...9 {
        let operation = BlockOperation {
            a[i] = 1
        }
        completionOperation.addDependency(operation)
        queue.addOperation(operation)
    }
    
    queue.addOperation(completionOperation)
    
    print("Done 

提交回复
热议问题