1

I have some task which I want to do asynchronously. So I am creating dispatchqueue in one class and doing some task.

//Adding Observer      
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil, queue: nil, using:catchNotification).

.

//Creating Background Thread.
     let anotherQueue = DispatchQueue(label: "Thread1", qos: .background)

    //Asynch thread.
    anotherQueue.async {
        for i in 0..<50 {
       print("\n ",i)
            sleep(1)
        }
    }

but upon some events I want to stop this, and am handling something like this.

func catchNotification (notification:Notification) -> Void {
    //Stop the queue.
    anotherQueue.suspend()
}

Am posting notification some other class. notification is getting received. but thread is not getting suspended.

Here is the complete class if you want to refer.

LoginPresenter.swift

let anotherQueue = DispatchQueue(label: "Thread1", qos: .background)
class LoginPresenter : LoginInteractor {
func catchNotification (notification:Notification) -> Void {
    //Stop the queue.
    anotherQueue.suspend()
}

func LoginSuccessFull()
{   
    NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil, queue: nil, using:catchNotification)

    //Asynch thread.
    anotherQueue.async {
        //Synch
        for i in 0..<50 {
       print("\n ",i)
            sleep(1)
        }
    }
}

or is any other better method or mechanism is there to do this ?

Ganesh
  • 89
  • 3
  • 14
  • Instead of this, you can show the user with ActivityView on the login screen and then once you get the catch notification stop it and dismiss the viewController. – Sachin Vas Jan 11 '17 at 11:26
  • The suspension occurs after completion of any blocks running at the time of the call. This is what written in https://developer.apple.com/reference/dispatch/dispatchobject/1452801-suspend. – Sachin Vas Jan 11 '17 at 11:28

1 Answers1

1

Reading Apple`s GCD documentation, you could see the following:

The suspension occurs after completion of any blocks running at the time of the call.

This means that, every block will be executed, what has already been started. Just create a second block in your LoginSuccessFull function like:

anotherQueue.async {
  print("this is the second block")
}

If you suspend straight after the function call, this block will not be executed.

If you would like to cancel immediately the operations in GCD, you will have to write you own implementation. But to how, it is always the one question for GCD, because it is just not designed that way.

The other option would be to use NSOperationQueue, but there you have implement right the cancel logic for your NSOperation subclasses.

Community
  • 1
  • 1
dirtydanee
  • 6,081
  • 2
  • 27
  • 43