Swift 是完美支持GCD的,由于Swift的发展写法也一直在变动,下面列举一些常见的用法。
全局队列异步执行
print("before" + "\(Thread.current)")
// 全局队列异步执行
DispatchQueue.global().async {
sleep(1)
print("asyncTask" + "\(Thread.current)")
}
// 全局队列同步执行
DispatchQueue.global().sync {
print("syncTask" + "\(Thread.current)")
}
print("after" + "\(Thread.current)")
// 执行结果
before<NSThread: 0x600000262d80>{number = 1, name = main}
syncTask<NSThread: 0x600000262d80>{number = 1, name = main}
after<NSThread: 0x600000262d80>{number = 1, name = main}
asyncTask<NSThread: 0x608000265b00>{number = 3, name = (null)}
可以看出同步执行时并没有重新开辟线程
GCD 常用模板
print("before" + "\(Thread.current)")
// 全局异步
DispatchQueue.global().async {
print("task" + "\(Thread.current)")
//主线程异步执行 刷新UI
DispatchQueue.main.async {
print("UI - task" + "\(Thread.current)")
}
}
print("after" + "\(Thread.current)")
// 打印结果
before<NSThread: 0x60800007d780>{number = 1, name = main}
after<NSThread: 0x60800007d780>{number = 1, name = main}
task<NSThread: 0x608000268e40>{number = 3, name = (null)}
UI - task<NSThread: 0x60800007d780>{number = 1, name = main}
日常使用以上模板足够了。