I tried running the following code and it raises the following error every time:
DispatchQueue.main.sync { }
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
I found this post on stackoverflow that says to never run synchronous code on the main queue:
DispatchQueue crashing with main.sync in Swift
I had assumed that because the sync { } method is there that means there is some context that it can be used. Is there absolutely no use for executing synchronous code on the main queue?
CodePudding user response:
I had assumed that because the sync { } method is there that means there is some context that it can be used.
Yes, it's there to be used when appropriate, but that doesn't mean it should be applied to the main queue.
Is there absolutely no use for executing synchronous code on the main queue?
The sync
command blocks and waits for its operation to be performed and completed on the specified queue. That queue can certainly be the main queue. But the queue that blocks cannot be the main queue! You must never say sync
when you are on the main queue, as you will then be blocking the main queue which is illegal; and you must really never say DispatchQueue.main.sync
when you are on the main queue, as you will be blocking the main queue forever (thereby causing the heat death of the universe).
Really the best thing to do is adopt async/await and never mention DispatchQueue again. All these concerns vanish in a puff of smoke and your code becomes safe and easy to reason about, automatically.
CodePudding user response:
sync should not be used in the main queue because you are likely to block everything, the method is there for "custom" queues (for example you created a queue and YOU handle when it has to be blocked and unblocked) the main queue is a special case, and since it is not manage by you introducing a block may generate unexpected behavior (that usually translates into a crash)