簡體   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