最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】swift中dispatch_async的含义

Swift crifan 2347浏览 0评论

看到ObjC代码:

- (void)exChangeMessageDataSourceQueue:(void (^)())queue {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), queue);
}

想要转换为swift代码

 

去搜:

swift  dispatch_async

参考:

Grand Central Dispatch Tutorial for Swift: Part 1/2 – Ray Wenderlich

Background Threads in Swift

 

后来知道了:

dispatch_async是iOS中的线程相关的GCD下面的一个函数

-》提供了一堆方便的函数,便于我们处理多线程的任务

-》基于系统提供的API,我自己另外加了点语法糖,变成了:

/***************************************************************************
 * GCD functions
 ***************************************************************************/

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 mainQueue = dispatch_get_main_queue()
    delayDispatch(delayTimeInSec, inThread: mainQueue, thingsTodo: thingsTodo)
}

func dispatchMain_sync(delayTimeInSec:Double = 0.0, thingsTodo:()->()) {
    delayDispatchInMainThread(delayTimeInSec, thingsTodo: thingsTodo)
}

func delayDispatchInBackgroundThread(delayTimeInSec:Double, thingsTodo:()->()) {
    let backgroundQueue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
//    let backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
    delayDispatch(delayTimeInSec, inThread: backgroundQueue, thingsTodo: thingsTodo)
}

func dispatchBackground_async(thingsTodo:()->()) {
    let backgroundQueue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
    dispatch_async(backgroundQueue, thingsTodo)
}

func dispatchUserInitiated_async(thingsTodo:()->()) {
    let userInitiatedQueue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
    dispatch_async(userInitiatedQueue, thingsTodo)
}

func dispatchMain_async(thingsTodo:()->()) {
    let mainQueue = dispatch_get_main_queue()
    dispatch_async(mainQueue, thingsTodo)
}

以便于后期使用。

更多代码详见:

crifanLib/swift at master · crifan/crifanLib · GitHub

https://github.com/crifan/crifanLib/tree/master/swift

转载请注明:在路上 » 【已解决】swift中dispatch_async的含义

发表我的评论
取消评论

表情

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.166 seconds, using 22.06MB memory