【已解决】swift中dispatch_async的含义

看到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



发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量