簡體   English   中英

如何快速取消 OperationQueue 中的特定操作

[英]How to cancel specific Operation from OperationQueue in swift

我的 OperationQueue 中有 3 個操作,我無法取消它們的特定操作。

我提到了這個例子,但我無法理解NSOperationQueue 取消特定操作

這是我的代碼

class myOperation1 : Operation {

    override func main() {

        print("op1 (🐭) working....")

        for i in 1...10 {
            print("🐭")
        }
    }
}

class myOperation2 : Operation {

    override func main() {

        print("op2 (🐶) working....")

        for i in 1...10 {
            print("🐶")
        }
    }
}

class myOperation3 : Operation {

    override func main() {

        print("op3 (🍉) working....")
        for i in 1...10 {
            print("🍉")
        }
    }
}

let op1 = myOperation1()
let op2 = myOperation2()
let op3 = myOperation3()

op1.completionBlock = {
    print("op1 (🐭) completed")
}

op2.completionBlock = {
    print("op2 (🐶) completed")
}

op3.completionBlock = {
    print("op3 (🍉) completed")
}

let opsQue = OperationQueue()
opsQue.addOperations([op1, op2, op3], waitUntilFinished: false)

DispatchQueue.global().asyncAfter(deadline: .now()) {
    opsQue.cancelAllOperations()
}

總之,我想從 operationQueue 中取消第二個操作。

請指導我。

謝謝

代碼中的opsQue.cancelAllOperations()導致從隊列中刪除未啟動的操作並為每個正在執行的操作調用Operation.cancel() ,但它僅將isCancelled設置為true 你需要明確地處理它

class myOperation2 : Operation {

    override func main() {

        print("op2 (🐶) working....")

        for i in 1...10 {
            if self.isCancelled { break } // cancelled, so interrupt
            print("🐶")
        }
    }
}

您可以調用 op2.cancel() 來取消操作,但是您需要采取額外的步驟來真正停止您的操作運行,因為 cancel() 僅將isCanceled屬性設置為 true。

請查看開發者文檔。 https://developer.apple.com/documentation/foundation/operation/1408418-iscancelled

此屬性的默認值為 false。 調用此對象的 cancel() 方法將此屬性的值設置為 true。 一旦取消,操作必須移動到完成狀態。

取消操作不會主動停止接收者的代碼執行。 操作對象負責定期調用此方法,並在該方法返回 true 時停止自身。

在為完成操作的任務而做任何工作之前,您應該始終檢查此屬性的值,這通常意味着在自定義 main() 方法的開頭檢查它。 可以在操作開始執行之前或執行期間的任何時間取消操作。 因此,檢查 main() 方法開頭的值(以及在整個方法中定期檢查)可以讓您在取消操作時盡快退出。

希望您參考 操作文檔

有幾個KVO-Compliant Properties 用於觀察操作。

有一個屬性isCancelled - read-only

用於在操作執行前檢查該屬性

像這樣:

class myOperation2 : Operation {

    override func main() {

        print("op2 (🐶) working....")

        if self.isCancelled {
            return
        }

        for i in 1...10 {
            print("🐶")
        }
    }
}

和取消:

DispatchQueue.global().asyncAfter(deadline: .now()) {
    opsQue.operations[1].cancel()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM