How to cancel specific Operation from OperationQueue in swift

operationqueue swift
blockoperation swift
swift operation states
swift operation cancel
subclass operation swift
nsoperationqueue swift 4 example stackoverflow
operation queue cancel all operations
serial operation queue swift

There are 3 Operations in my OperationQueue and i'm not able to cancel specific operation from them.

I referred this example but i can't understand it NSOperationQueue cancel specific operations

This is my code

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

Inshort i want to cancel second operation from operationQueue.

Please guide me.

Thank you

you can call op2.cancel() to cancel the operation, but you need to take additional steps to really stop your operation from running as cancel() only set the isCanceled property to true.

Please check the developer document. https://developer.apple.com/documentation/foundation/operation/1408418-iscancelled

The default value of this property is false. Calling the cancel() method of this object sets the value of this property to true. Once canceled, an operation must move to the finished state.

Canceling an operation does not actively stop the receiver’s code from executing. An operation object is responsible for calling this method periodically and stopping itself if the method returns true.

You should always check the value of this property before doing any work towards accomplishing the operation’s task, which typically means checking it at the beginning of your custom main() method. It is possible for an operation to be cancelled before it begins executing or at any time while it is executing. Therefore, checking the value at the beginning of your main() method (and periodically throughout that method) lets you exit as quickly as possible when an operation is cancelled.

cancelAllOperations(), OperationQueue; cancelAllOperations() iOS 2.0+; macOS 10.5+; Mac Catalyst 13.0+; tvOS 9.0+; watchOS 2.0+ This method calls the cancel() method on all operations currently in the queue. Adds the specified operations to the queue. Whenever the operation queue is added to queue, it will be ready to execute. On the other hand, we use a timer to cancel the download queue. As soon as an operation queue is cancelled, it notifies

opsQue.cancelAllOperations() in your code cause removing non-started operations from queue and calls Operation.cancel() for each executing operation, but it only set isCancelled to true. You need to handle it explicitly

class myOperation2 : Operation {

    override func main() {

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

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

cancel, iOS 2.0+; macOS 10.5+; Mac Catalyst 13.0+; tvOS 9.0+; watchOS 2.0+ Canceling an operation that is currently in an operation queue, but not yet executing,� You can override this behavior if you need something specific: queue.maxConcurrentOperationCount = 4. And if you ever need to stop all operations that have yet to be started, call cancelAllOperations () on your queue, like this: queue.cancelAllOperations() That won’t cancel any operations that are currently in flight.

Hope you referred to the documentation for Operation

There are several KVO-Compliant Properties for observe operation.

There is one property isCancelled - read-only

used to check this property before the execution of the operation

like this:

class myOperation2 : Operation {

    override func main() {

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

        if self.isCancelled {
            return
        }

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

and for cancelation:

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

Canceling Operations with Dependencies, So I choose OperationQueue (a.k.a. NSOperationQueue ), which supports cancellation. Each step of the task can be modeled as a single� Canceling an operation causes the operation to ignore any dependencies it may have. This behavior makes it possible for the queue to execute the operation’s start () method as soon as possible. The start () method, in turn, moves the operation to the finished state so that it can be removed from the queue.

Operation and OperationQueue Tutorial in Swift, Concurrency in Swift (Operations and Operation Queue Part 3) and Custom Operations to run tasks async; How to cancel operations; What is if you cannot make progress until all of the specified tasks are completed. Canceling an operation object leaves the object in the queue but notifies the object that it should stop 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.

Concurrency in Swift (Operations and Operation Queue Part 3), Operation Queue is a special queue to which we can add our If we would like to cancel all tasks that are currently inside an operation queue to a certain operation object or to the whole operation queue. An NSOperation Queue does not dequeue an operation until finished changes to true, so it is critical to implement this correctly in subclasses to avoid deadlock. Cancellation. It is often useful to cancel operations early to prevent needless work from being performed, whether due to a failure in a dependent operation or explicit cancellation by

Basics of Operations and Operation Queues in iOS • intent, Learn Swift coding for iOS with these free tutorials. You can even ask the operation queue to wait until all its operations are finished, which makes scheduling easier. If you had You can override this behavior if you need something specific: That won't cancel any operations that are currently in flight. The only way to dequeue an operation is to cancel it. You can cancel a single individual operation object by calling its cancel method or you can cancel all of the operation objects in a queue by calling the cancelAllOperations method of the queue object. You should cancel operations only when you are sure you no longer need them.

Comments
  • op2.cancel() doesn't work?
  • yes it works for op2 but for other it won't worked
  • Excerpt from apple's Foundation.NSOperation.swift: "access to operations is inherently a race condition, it should not be used"