简体   繁体   English

操作 queuePriority 未按预期工作

[英]Operation queuePriority not working as expected

I'm trying to explore queuePriority of Operation.我正在尝试探索 queuePriority of Operation。 I have three Operation objects with queuePriority veryhigh,high and normal.我有三个具有 queuePriority 非常高、高和正常的操作对象。 But I'm getting unexpected output, in log I can see Operation objects with queuePriority veryhigh not always executing first.但是我得到了意想不到的 output,在日志中我可以看到 queuePriority 非常高的操作对象并不总是首先执行。 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 Output: op1 executionBlock op0 executionBlock #1 op0 executionBlock #2 op2 executionBlock op1 completionBlock op0 completionBlock op2 completionBlock

If you want this kind of behavior,you should add dependencies between operations.如果你想要这种行为,你应该在操作之间添加依赖关系。 queuePriorites does not guarantee execution order. queuePriorites 不保证执行顺序。 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. op2 将等待 op1,op1 将等待 op0。 So, the order will be op0 -> op1 -> op2所以,顺序是 op0 -> op1 -> op2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM