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

时间:2018-10-04 06:17:59

标签: ios swift dispatch-queue

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用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