调用.cancel()时DispatchWorkItem不终止功能

ch1*_*era 4 grand-central-dispatch ios swift alamofire dispatchworkitem

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

taskWorkItems.append(DispatchWorkItem { [weak self] in
    concurrentQueue!.async {
        runTask(task: task)
    }
})
Run Code Online (Sandbox Code Playgroud)

然后,我迭代工作项的数组并按如下所示调用perform()函数:

for workItem in taskWorkItems {
    workItem.perform()
}
Run Code Online (Sandbox Code Playgroud)

最后,我的应用程序中有一个按钮,当点击该按钮时,我想取消工作项,并且使用以下代码来实现这一目的:

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

        print(workItem.isCancelled)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Eri*_*c H 7

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()
}
Run Code Online (Sandbox Code Playgroud)