Operation queuePriority not working as expected

76 Views Asked by At

I'm trying to explore queuePriority of Operation. I have three Operation objects with queuePriority veryhigh,high and normal. But I'm getting unexpected output, in log I can see Operation objects with queuePriority veryhigh not always executing first. Please help.

    let operationQueue = OperationQueue()
    let op1 = BlockOperation()
    let op2 = BlockOperation()
    let op0 = BlockOperation()
    op0.completionBlock = {
        print("op0 completionBlock")
    }
    op0.addExecutionBlock {
        print("op0 executionBlock #1")
    }
    op0.addExecutionBlock {
        print("op0 executionBlock #2")
    }
    op0.queuePriority = .veryHigh

    op1.completionBlock = {
        print("op1 completionBlock")
    }
    op1.addExecutionBlock {
        print("op1 executionBlock")
    }
    op1.queuePriority = .high

    op2.completionBlock = {
        print("op2 completionBlock")
    }
    op2.addExecutionBlock {
        print("op2 executionBlock")
    }
    op2.queuePriority = .normal

    operationQueue.addOperations([op2, op1, op0], waitUntilFinished: true)

Output: op1 executionBlock op0 executionBlock #1 op0 executionBlock #2 op2 executionBlock op1 completionBlock op0 completionBlock op2 completionBlock

1

There are 1 best solutions below

2
yalcin On

If you want this kind of behavior,you should add dependencies between operations. queuePriorites does not guarantee execution order. System tries to execute high priory tasks before low priority tasks but this depends on various factors and there is no guarantee. You should implement dependencies like below;

op2.addDependency(op1)
op1.addDependency(op0)

op2 will wait op1 and op1 will wait op0. So , the order will be op0 -> op1 -> op2