简体   繁体   English

使用 swift 在全局范围内停止 dispatchquene().async

[英]stop dispatchquene().async in loop globally using swift

override func viewDidLoad() {
  super.viewDidLoad()    
            worktask = DispatchWorkItem {
                   for i in 1…4 {
                         sleep(2)
                          DispatchQueue.main.async {
                                 // run code
                                 fucntionAlert()
                           }
                   }
             }
            DispatchQueue.global().async(execute: worktask)
    }
    func fucntionAlert(){   
            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
                DispatchQueue.global().sync {
                            self.worktask.cancel()
                 }
            }
    }

    @IBAction func action(_sender: Any){
            DispatchQueue.global().sync {
                 self.worktask.cancel()
            }
    }

I'm trying to run dispatchqueue for 4 times, each one starts after 2 seconds.我试图运行 dispatchqueue 4 次,每一次都在 2 秒后启动。 Like timer.像计时器。 I don't want to use timer because i have timer already running in uiapplication.我不想使用计时器,因为我已经在 uiapplication 中运行了计时器。

Now I'm trying to stop the dispatchqueue when moving to next view controller or clicking ok button.现在我试图在移动到下一个视图控制器或单击确定按钮时停止调度队列。 It still running and never stops.它仍在运行,永不停止。 Any solution?有什么解决办法吗?

i need to stop when moving to next view controller and starts again when return to myviewcontroller.我需要在移动到下一个视图控制器时停止,并在返回到 myviewcontroller 时再次启动。 thanks!谢谢!

Try this code below.试试下面的这段代码。

    worktask = DispatchWorkItem { [weak self] in
        for i in 1...4 {
            sleep(2)
            if self?.worktask?.isCancelled ?? true {
                break
            }
            DispatchQueue.main.async {
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM