Why does it matter from where you call DispatchQueue.main.async?

Why does it matter from where you call DispatchQueue.main.async?



I wrote the following pieces of code:


DispatchQueue.main.async
self.cameraManager.checkForCameraAuthorization(deniedCallback:
self.presentDeniedAlert()
self.activityIndicator.stopAnimating()
)
self.cameraAccess = true
self.cameraButton.isEnabled = false
self.activityIndicator.stopAnimating()




and


cameraManager.checkForMicrophoneAuthorization(deniedCallback:
self.presentDeniedAlert()
self.activityIndicator.stopAnimating()
)
DispatchQueue.main.async
self.microphoneAccess = true
self.microphoneButton.isEnabled = false
self.activityIndicator.stopAnimating()


}



(the difference is from where async is called)



The 1. crashes self.cameraButton.isEnabled = false can only be called from main thread


self.cameraButton.isEnabled = false can only be called from main thread



The 2. one finishes just fine.



Can someone explain, why this is so?




2 Answers
2



The diff is as explained below.



In the 1st code your checkForCameraAuthorization callback is executing in a different thread, and you should know UIApplication/UI related task should execute in the main thread.


checkForCameraAuthorization



In the 2nd code after getting the callback in checkForCameraAuthorization you are executing the UI related task in the main thread, so its works fine.


checkForCameraAuthorization



If any doubt plz comment.






So that the function is called from .main.async doesn't mean that the callback is called in this thread? E.g. the callback is still not called from .main.async, right?

– Bruce
Sep 16 '18 at 17:34







Yes right, you submitted entire task into main queue, but that doesn't mean callback will also happen in the main queue.

– vivekDas
Sep 16 '18 at 17:54



Dispatch queues are thread-safe which means that you can access them from multiple threads simultaneously. Always update UI elements from the main queue.



In first code you are updating UI on different threads not from Main Thread.



For more Refrences you can follow these link -



https://www.quora.com/Why-must-the-UI-always-be-updated-on-Main-Thread#



https://www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)