如何停止现有调度队列并重新开始?


@objc func textFieldChanged(_ textField: UITextField) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
self.shouldEnableBtn()
})
}

在这里,如果我再次输入 textFieldChanged,我想取消现有的调度并重新开始。

您可以使用DispatchWorkItem类,它允许您单独取消任务。

let workItem = DispatchWorkItem {
self.shouldEnableBtn()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: workItem)
// To cancel the work-item task
workItem.cancel()

最好将OperationQueue用于此任务,如下所示:

let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
// Add operation in the queue
operationQueue.addOperation {
self.shouldEnableBtn()
}
// Cancel to on-going operation by
operationQueue.cancelAllOperations()
// Pause to on-going operation by
operationQueue.isSuspended = true

最新更新