【问题标题】:How to stop existing dispatchqueue and start new?如何停止现有的调度队列并开始新的?
【发布时间】:2018-10-04 06:17:58
【问题描述】:
    @objc func textFieldChanged(_ textField: UITextField) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
            self.shouldEnableBtn()
        })
}

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

【问题讨论】:

标签: ios swift dispatch-queue


【解决方案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

【讨论】:

  • 谢谢,我不能使用操作队列,因为它包含 UI。对于第一个示例,我需要先取消现有的,然后再创建新的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多