iOS异步变成同步

iOS异步变成同步,第1张

有些时候会有一些特殊的需求,让一些异步 *** 作变成同步,我记录了如下的几种方式,备用:
func oneAsynTask(callback: @escaping (Int)->Void) {
        DispatchQueue.global().async {
            print("task running")
            sleep(5)
            callback(5)
            print("task finsh")
        }
    }
way1
  func waitToFinishWay1() {
       /// 信号量实现
        DispatchQueue.global().async {
            let semp = DispatchSemaphore(value: 0)
            var returnValue: Int = 0
            self.oneAsynTask { value in
                returnValue = value
                semp.signal()
            }
            print("waiting ...")
            semp.wait()
            print("waiting finsh")
            print("returnValue:\(returnValue)")
        }
    }
way2
func waitToFinishWay2() {
    DispatchQueue.global().async {
        var returnValue: Int = 0
        let condition = NSCondition()
        condition.lock()
        self.oneAsynTask { value in
            returnValue = value
            condition.signal()
        }
        print("waiting ...")
        while returnValue == 0 { // 加这个,是为了可能还没有开始等待,上面的异步任务已经完成
            condition.wait()
        }
        
        condition.unlock()
        print("waiting finsh")
        print("returnValue:\(returnValue)")
    }
}
way3
func waitTOFinishWay3() {
    DispatchQueue.global().async {
        var returnValue: Int = 0
        let group = DispatchGroup()
        group.enter()
        self.oneAsynTask { value in
            returnValue = value
            group.leave()
        }
        print("waiting ...")
        group.wait()
        print("waiting finsh")
        print("returnValue:\(returnValue)")
        
    }
}
way4
func waitToFinshWay4() {
    DispatchQueue.global().async {
        var returnValue: Int = 0
        let group = DispatchGroup()
        group.enter()
        self.oneAsynTask { value in
            returnValue = value
            group.leave()
        }
        print("waiting ...")
        while returnValue == 0 {
            
        }
        print("waiting finsh")
        print("returnValue:\(returnValue)")
        
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/996854.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存