繁体   English   中英

调用.cancel()时DispatchWorkItem不终止函数

[英]DispatchWorkItem not terminating function when .cancel() is called

我在主函数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 我做错了什么,如何停止执行我的功能?

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()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM