Reputation: 2666
I am having some trouble understanding dispatch.async
. I have the following code:
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.rawValue), 0)) {
print("hello")
print("world")
dispatch_async(dispatch_get_main_queue()) {
print("done")
}
}
Yet the only thing that it printed out is:
hello
No matter what I do, only the first line is executed. If I replace it with a function, like so:
func printHelloWorld(){
print("hello")
print("world")
}
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.rawValue), 0)) {
printHelloWorld()
dispatch_async(dispatch_get_main_queue()) {
print("done")
}
}
The same thing happened. The function is called, but the only the first line of executable code is run. In addition, the closure to be called when the thread finished is not being called at all.
Any help understanding how to use dispatch.async
would be greatly appreciated.
Upvotes: 2
Views: 72
Reputation: 10782
Playgrounds stop executing once the main thread is done running top level code. You can use this line of code to keep the playground running if you're running asynchronous code:
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
And then use this line of code once you're done:
XCPlaygroundPage.currentPage.finishExecution()
Upvotes: 3