【问题标题】:DispatchWorkItem not terminating function when .cancel() is called调用 .cancel() 时,DispatchWorkItem 未终止函数
【发布时间】:2018-10-03 20:28:36
【问题描述】:

我在主函数runTask() 中调用的函数列表中使用 Alamofire 按顺序发出了一系列 HTTP 请求,我希望能够停止这些请求。因此,我在DispatchWorkItem 中为我需要运行的每个任务设置了runTask() 函数调用,并将工作项存储在一个数组中,如下所示:

taskWorkItems.append(DispatchWorkItem { [weak self] in
    concurrentQueue!.async {
        runTask(task: task)
    }
})

然后,我迭代工作项数组并像这样调用perform() 函数:

for workItem in taskWorkItems {
    workItem.perform()
}

最后,我的应用中有一个按钮,我想在点击时取消工作项,我有以下代码可以实现这一点:

for workItem in taskWorkItems {
    concurrentQueue!.async {
        workItem.cancel()

        print(workItem.isCancelled)
    }
}

workItem.isCancelled 打印到true;但是,我在runTask() 调用的函数中设置了日志,即使调用了workItem.cancel() 并且workItem.isCancelled 打印了true,我仍然看到这些函数正在执行。我做错了什么,如何停止执行我的功能?

【问题讨论】:

  • workItem 的isCancelled 属性指出任务当前是否被取消。如果您取消一个 WorkItem,如果执行尚未开始,则该任务将被完全取消。如果它开始并被取消,isCancelled 属性将指示true,因此您可以实现您的取消逻辑。关于如何在 Alamofire stackoverflow.com/questions/41478122/cancel-a-request-alamofire 上取消请求有一个先前的答案,如果需要,您应该在您的工作项逻辑中执行 request.cancel() 函数。
  • @Orlando 这正是我所需要的,谢谢!

标签: ios swift alamofire grand-central-dispatch dispatchworkitem


【解决方案1】:

TLDR:如果任务尚未运行,调用 cancel 将停止执行,但不会停止已经执行的任务。

因为关于这方面的苹果文档是陈旧的......

https://medium.com/@yostane/swift-sweet-bits-the-dispatch-framework-ios-10-e34451d59a86

A dispatch work item has a cancel flag. If it is cancelled before running, the dispatch queue won’t execute it and will skip it. If it is cancelled during its execution, the cancel property return True. In that case, we can abort the execution

//create the dispatch work item
var dwi2:DispatchWorkItem?
dwi2 = DispatchWorkItem {
    for i in 1...5 {
        print("\(dwi2?.isCancelled)")
        if (dwi2?.isCancelled)!{
            break
        }
        sleep(1)
        print("DispatchWorkItem 2: \(i)")
    }
}
//submit the work item to the default global queue
DispatchQueue.global().async(execute: dwi2!)

//cancelling the task after 3 seconds
DispatchQueue.global().async{
    sleep(3)
    dwi2?.cancel()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 2020-05-22
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多