Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: synchronously perform code in background; queue.sync does not work as I would expect

I would like to perform some code synchronously in the background, I really thought this is the way to go:

let queue = DispatchQueue.global(qos: .default)
queue.async {
    print("\(Thread.isMainThread)")
}

but this prints true unless I use queue.async. async isn't possible as then the code will be executed in parallel. How can I achieve running multiple blocks synchronously in the background?

What I would like to achieve: synchronize events in my app with the devices calendar, which happens in the background. The method which does this can be called from different places multiple times so I would like to keep this in order and in the background.

like image 321
swalkner Avatar asked Jun 27 '17 06:06

swalkner


1 Answers

Async execution isn't your problem, since you only care about the order of execution of your code blocks relative to each other but not relative to the main thread. You shouldn't block the main thread, which is in fact DispatchQueue.main and not DispatchQueue.global.

What you should do is execute your code on a serial queue asynchronously, so you don't block the main thread, but you still ensure that your code blocks execute sequentially.

You can achieve this using the following piece of code:

let serialQueue = DispatchQueue(label: "serialQueue")
serialQueue.async{  //call this whenever you need to add a new work item to your queue
    //call function here
}
like image 101
Dávid Pásztor Avatar answered Sep 20 '22 17:09

Dávid Pásztor