如何在swift中使用线程?
dispatchOnMainThread:^{
NSLog(@"Block Executed On %s", dispatch_queue_get_label(dispatch_get_current_queue()));
}];发布于 2014-08-01 07:15:43
Swift 3.0+
在Swift 3.0中有很多已经被modernized了。在后台队列上运行某项操作如下所示:
DispatchQueue.global(qos: .userInitiated).async {
print("This is run on a background queue")
DispatchQueue.main.async {
print("This is run on the main queue, after the previous code in outer block")
}
}Swift 1.2到2.3
let qualityOfServiceClass = QOS_CLASS_USER_INITIATED
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
print("This is run on a background queue")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print("This is run on the main queue, after the previous code in outer block")
})
})Swift 1.2之前的- Known问题
在Swift 1.1中,苹果在没有做一些修改的情况下不支持上面的语法。传递QOS_CLASS_USER_INITIATED实际上并不起作用,而是使用Int(QOS_CLASS_USER_INITIATED.value)。
有关更多信息,请参阅Apples documentation
发布于 2016-12-06 22:25:22
Dan Beaulieu在swift5中的回答(也是从swift 3.0.1开始工作的)。
Swift 5.0.1
extension DispatchQueue {
static func background(delay: Double = 0.0, background: (()->Void)? = nil, completion: (() -> Void)? = nil) {
DispatchQueue.global(qos: .background).async {
background?()
if let completion = completion {
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
completion()
})
}
}
}
}用法
DispatchQueue.background(delay: 3.0, background: {
// do something in background
}, completion: {
// when background job finishes, wait 3 seconds and do something in main thread
})
DispatchQueue.background(background: {
// do something in background
}, completion:{
// when background job finished, do something in main thread
})
DispatchQueue.background(delay: 3.0, completion:{
// do something in main thread after 3 seconds
})发布于 2015-06-15 17:13:44
最佳实践是定义一个可以多次访问的可重用函数。
可重用函数:
例如,像AppDelegate.swift这样的全局函数。
func backgroundThread(_ delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
background?()
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion?()
}
}
}注意:在Swift 2.0中,将上面的QOS_CLASS_USER_INITIATED.value替换为QOS_CLASS_USER_INITIATED.rawValue
使用:
A.在后台运行延迟为3秒的进程:
backgroundThread(3.0, background: {
// Your background function here
})B.要在后台运行进程,然后在前台运行完成:
backgroundThread(background: {
// Your function here to run in the background
},
completion: {
// A function to run in the foreground when the background thread is complete
})C.延迟3秒-注意使用完成参数,不带后台参数:
backgroundThread(3.0, completion: {
// Your delayed function here to be run in the foreground
})https://stackoverflow.com/questions/24056205
复制相似问题