我使用GCD执行后台执行。但是在我的ViewController类中有按钮。一旦用户点击按钮,我怎么能在执行之间停止GCD? 这是我的代码
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.value), 0), {
self.StartProcess()
})
@IBAction func buttonIsClicked(sender: AnyObject) {
// how to stop GCD execution?
}
答案 0 :(得分:-1)
创建一个NSThread数组并取消最后一个元素。
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()
}
答案 1 :(得分:-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")
})
})
}
停止该计时器并按下按钮上的后台执行 timer.invalidate()
然后通过计时器
调用此方法var timer = NSTimer(timeInterval: 1.0, target: self, selector: "someBackgroundTask:", userInfo: nil, repeats: true)
@IBAction func buttonIsClicked(sender: AnyObject) {
timer.invalidate()
}