2

I used GCD to perform the background execution. however in my ViewController class there is button . How i can stop the GCD in between the execution once user click on button ? here is my code

 dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.value), 0), {
                        self.StartProcess()
                    })      
 @IBAction func buttonIsClicked(sender: AnyObject) {
// how to stop GCD execution?
}
Rizwan Shaikh
  • 2,824
  • 2
  • 27
  • 49
  • 1
    you'll need a variable to communicate from your IBAction to the background thread, that it should stop. The background thread has to query the variable regularly. – Volker Apr 21 '15 at 07:20
  • There is no means by which to (safely) forcibly cancel in-flight operations, regardless of the method used to dispatch them. This is true in Swift as well as in Objective-C (and, more generally, in *any* non-garbage-collected runtime). You have to set up a way to inform the in-flight operation that it should clean up, and return early. This has been addressed many times in other questions, including (by me) here: http://bit.ly/1OCirkM and here: http://bit.ly/1Dd2zjo – ipmcc Apr 21 '15 at 16:28

2 Answers2

-1

Create an NSThread array and cancel the last element.

var threads = [NSThread]()
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.value), 0), {
                        self.StartProcess()
                        threads.append(NSThread.currentThread())
                    })      

@IBAction func buttonIsClicked(sender: AnyObject) {
     threads.last.cancel()
}
  • That is much to complicated, why not just stopping to process if a variable is set to stop? – Volker Apr 21 '15 at 07:27
  • This does not actually do anything to stop execution. It merely marks the thread as cancelled. The code running in that thread must explicitly check to see if the thread has been canceled and exit early. Just calling `cancel` doesn't actually do anything. See the docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/index.html#//apple_ref/occ/instm/NSThread/cancel – ipmcc Apr 21 '15 at 16:31
-1
      func someBackgroundTask(timer:NSTimer) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
            println("do some background task")

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                println("update some UI")

            })
    })
}

stop that timer and the background execcution on button click

timer.invalidate()

and then call this method through timer

var timer = NSTimer(timeInterval: 1.0, target: self, selector: "someBackgroundTask:", userInfo: nil, repeats: true)

@IBAction func buttonIsClicked(sender: AnyObject) {
          timer.invalidate()
}
bLacK hoLE
  • 781
  • 1
  • 7
  • 20