美文网首页
GCD处理任务和runloop的关系

GCD处理任务和runloop的关系

作者: 月禅 | 来源:发表于2023-03-29 17:23 被阅读0次
    var count = 0
        var timer: Timer? = nil
        func test() {
            let queue = DispatchQueue(label: "aaa")
            queue.async {
                print("start\(Thread.current)")
                queue.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: 1), execute: DispatchWorkItem(block: {
                    print("1s后执行异步任务\(Thread.current)")
                }))
                self.perform(#selector(self.perfromTask), with: nil, afterDelay: 2)
                self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
                    print("定时任务\(Thread.current)")
                    self.count += 1
                    if self.count > 10 {
                        self.timer?.invalidate()
                        self.timer = nil
                    }
                }
                RunLoop.current.add(self.timer!, forMode: .common)
                RunLoop.current.run()
            }
        }
        
        
        @objc func perfromTask() {
            print("perform 延时任务\(Thread.current)")
        }
        /**
         start<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         perform 延时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         定时任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}
         1s后执行异步任务<NSThread: 0x6000000bc6c0>{number = 7, name = (null)}     //(timer任务会卡住当前线程)
         */
    

    相关文章

      网友评论

          本文标题:GCD处理任务和runloop的关系

          本文链接:https://www.haomeiwen.com/subject/nlwfddtx.html