最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

[已解决]swift中延迟运行在非主线程的别的线程

Swift crifan 708浏览 0评论

延迟运行,在主线程的话,之前已经实现:

func delayDispatchInMainThread(delayTimeInSec:Double, thingsTodo:()->()) {
    let dispatchDelayTime = dispatch_time(
        DISPATCH_TIME_NOW,
        Int64(delayTimeInSec * Double(NSEC_PER_SEC))
    )
    dispatch_after(dispatchDelayTime, dispatch_get_main_queue(), thingsTodo)
}
delayDispatchInMainThread(deayTimeInSec, thingsTodo: self.closeCurrentAndReturnToMain)

swift delay function non main thread

swift delay function other thread

swift dispatch_after non main thread

In Swift how to call method with parameters on GCD main thread? – Stack Overflow

swift dispatch background  thread

ios – How to use background thread in swift? – Stack Overflow

最后暂时用代码:

            //delay to save message list
            let qualityOfServiceClass = QOS_CLASS_BACKGROUND
            let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
            let dispatchDelayTime = dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(0.2 * Double(NSEC_PER_SEC))
            )
            dispatch_after(dispatchDelayTime, backgroundQueue, {
                msgTVC.storeData()
            })

最后优化为:

            //delay to save message list
            delayDispatchInBackgroundThread(0.2, thingsTodo: {
                msgTVC.storeData()
            })
func delayDispatch(delayTimeInSec:Double, inThread:dispatch_queue_t, thingsTodo:()->()) {
    let dispatchDelayTime = dispatch_time(
        DISPATCH_TIME_NOW,
        Int64(delayTimeInSec * Double(NSEC_PER_SEC))
    )
   
    dispatch_after(dispatchDelayTime, inThread, thingsTodo)
}
func delayDispatchInMainThread(delayTimeInSec:Double, thingsTodo:()->()) {
//    let dispatchDelayTime = dispatch_time(
//        DISPATCH_TIME_NOW,
//        Int64(delayTimeInSec * Double(NSEC_PER_SEC))
//    )
//   
//    let mainQueue = dispatch_get_main_queue()
//
//    dispatch_after(dispatchDelayTime, mainQueue, thingsTodo)
   
    let mainQueue = dispatch_get_main_queue()
    delayDispatch(delayTimeInSec, inThread: mainQueue, thingsTodo: thingsTodo)
}
func delayDispatchInBackgroundThread(delayTimeInSec:Double, thingsTodo:()->()) {
//    let dispatchDelayTime = dispatch_time(
//        DISPATCH_TIME_NOW,
//        Int64(delayTimeInSec * Double(NSEC_PER_SEC))
//    )
//   
//    let backgroundQueue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
//
//    dispatch_after(dispatchDelayTime, backgroundQueue, thingsTodo)
    let backgroundQueue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
    delayDispatch(delayTimeInSec, inThread: backgroundQueue, thingsTodo: thingsTodo)
}

转载请注明:在路上 » [已解决]swift中延迟运行在非主线程的别的线程

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
67 queries in 0.240 seconds, using 18.87MB memory