我使用swift 3.0.2。 Xcode 8.3.1
我尝试使用isSuspended = true
属性,但它不会停止操作。
当我取消一个operation1
时,所有其他依赖于operation1
的操作会立即启动。
我希望他们等到我告诉他们。
请帮助我!
EDIT1:
意思是它不会停止操作:
我有操作等级oq
和三个操作:op1
,op2
,op3
oq.addOperation(op1)
op2.addDependency(op1)
oq.addOperation(op2)
op3.addDependency(op2)
oq.addOperation(op3)
所有三个操作都需要10秒才能执行。
在我添加第三个操作后,我设置了isSuspended = true
My log:
op1 started
(-- set `isSuspended` to true)
(after 10 seconds)
op2 started
(after 10 seconds)
op3 started
当我将isSuspended
设置为true时,我认为op1正在执行,没关系。但为什么op2开始???
这是我的File.swift
:
import Foundation
class PendingOps {
// lazy var downloadInProgress = [Int: Operation]()
// current tracklist
var downloadQueue: OperationQueue {
let queue = OperationQueue()
queue.qualityOfService = .background
queue.name = "Offline queue"
queue.maxConcurrentOperationCount = 1
return queue
}
}
class op: Operation {
var nam:String = ""
init(nam: String) {
self.nam = nam
}
override func main() {
print("\(self.nam) started");
sleep(10)
print("\(self.nam) ended");
}
}
这是ViewController's
viewDidLoad()
函数:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let test = PendingOps()
let o1 = op(nam: "o1")
let o2 = op(nam: "o2")
o2.addDependency(o1)
let o3 = op(nam: "o3")
o3.addDependency(o2)
test.downloadQueue.addOperation(o1)
test.downloadQueue.isSuspended = true
print(test.downloadQueue.isSuspended)
test.downloadQueue.addOperation(o2)
test.downloadQueue.addOperation(o3)
}
答案 0 :(得分:1)
您的计算属性downloadQueue
会在每次调用时创建一个独立队列。即您正在挂起第一个创建的队列,但第二个和第三个队列不受影响。
要解决此问题,请仅在init()
class PendingOps {
var downloadQueue: OperationQueue!
init() {
let queue = OperationQueue()
queue.qualityOfService = .background
queue.name = "Offline queue"
queue.maxConcurrentOperationCount = 1
downloadQueue = queue
}
}
游乐场样本:
class PendingOps {
var downloadQueue: OperationQueue!
init() {
let queue = OperationQueue()
queue.qualityOfService = .background
queue.name = "Offline queue"
queue.maxConcurrentOperationCount = 1
downloadQueue = queue
}
}
class op: Operation {
var nam:String = "?"
init(nam: String) {
self.nam = nam
}
override func main() {
print("\(self.nam) started");
sleep(1)
print("\(self.nam) ended");
}
}
func didLoad() {
let test = PendingOps()
let o1 = op(nam: "o1")
let o2 = op(nam: "o2")
o2.addDependency(o1)
let o3 = op(nam: "o3")
o3.addDependency(o2)
test.downloadQueue.addOperation(o1)
test.downloadQueue.isSuspended = true
print(test.downloadQueue.isSuspended)
test.downloadQueue.addOperation(o2)
test.downloadQueue.addOperation(o3)
}
didLoad()
PlaygroundPage.current.needsIndefiniteExecution = true
打印:
o1 started
true
o1 ended