IOS多线程之NSOperation(3)

IOS多线程之NSOperation(3)

操作优先级和服务质量

可以通过QueuePriority属性来设置operation在队列中的执行优先级

public enum QueuePriority : Int, @unchecked Sendable {
    case veryLow = -8
    case low = -4
    case normal = 0
    case high = 4
    case veryHigh = 8
}

IOS8.0之后推荐使用QualityOfService来设置operation在队列中的服务质量

@available(iOS 8.0, *)
public enum QualityOfService : Int, @unchecked Sendable {
    case userInteractive = 33
    case userInitiated = 25
    case utility = 17
    case background = 9
    case `default` = -1
}

创建三个Operation

let op1 = BlockOperation {
    print("op1")
}
let op2 = BlockOperation {
    print("op2")
}
let op3 = BlockOperation {
    print("op3")
}

queue.addOperations([op1,op2,op3], waitUntilFinished: true)

设置其queuePriority

op1.queuePriority = .low
op2.queuePriority = .high
op3.queuePriority = .veryHigh

queue.addOperations([op1,op2,op3], waitUntilFinished: true)

//打印
/*
op3
op2
op1
*/

设置其qualityOfService

op1.qualityOfService = .background
op2.qualityOfService = .utility
op3.qualityOfService = .userInitiated

//打印
/*
op3
op2
op1
*/

操作间依赖

Operation 之间可以通过以下方法添加/移除依赖来保证执行顺序

//添加依赖
open func addDependency(_ op: Operation)
//移除依赖
open func removeDependency(_ op: Operation)

比如op1依赖于op3,op3依赖于op2

不可以相互依赖

执行顺序为op2 -> op3 -> op1

op1.addDependency(op3)
op3.addDependency(op2)

//打印
/*
op2
op3
op1
*/

可以在不同队列中添加依赖

将op1,op2,op3添加到我们的OperationQueue

新建一个op4依赖于op1,将op4添加到主线程队列

let op4 = BlockOperation {
    print("主线程op4")
}

op4.addDependency(op1)
op1.addDependency(op3)
op3.addDependency(op2)

OperationQueue.main.addOperation(op4)

//打印
/*
op2
op3
op1
主线程op4
*/
posted @ 2023-04-05 17:48  R1cardo  阅读(29)  评论(0编辑  收藏  举报