operation.cancel() 未取消当前操作

operation.cancel() not cancelling current operation

使用operation.cancel() 不会取消当前操作。如果队列中有操作,它似乎会取消它,但如果它正在执行,那么它似乎不会停止它。

我是否需要在我的子类化操作中将某些内容发送回 main() 函数以使其停止?

for operation in downloadQueue.operations {
    if operation.name == opName {
        if operation.isExecuting == true {
           operation.cancel()
        }
    }
}

参见文档:https://developer.apple.com/reference/foundation/operationqueue

Canceling an operation object leaves the object in the queue but notifies the object that it should abort its task as quickly as possible. For currently executing operations, this means that the operation object’s work code must check the cancellation state, stop what it is doing, and mark itself as finished.

基本上您的操作代码应该检查 isCancelled 并在需要时停止。例如,您可能有一个循环处理数据项,您可以在处理每个项目之前检查 isCancelled。