main.async vs main.sync() vs global().async in Swift3 GCD

asynchronous, ios, multithreading, swift

Solution

In simple term i come to conclusion that -

- Queue- There are 3 Types of Queue i.e. 1 Main Queue, 4 Global Queue and Any No. of Custom Queues.

- Threads- One is Main Thread and other background threads which system provides to us.

DispatchQueue.main.async

-It means performing task in main queue with using of background thread (w/o blocking of UI) and when task finish it automatic Updated to UI because its already in Main Queue.

DispatchQueue.global().async along with global().sync

It means performing task in Global Queue with using of background thread and when task finish, than global().sync use bring the work from globalQueue to mainQueue which update to UI.

Reason of My App Crash

I was trying to bring the completed task to MainQueue by using(main.sync), but it was already on MainQueue because i hadnt switched the Queue, and this create DeadLock (MainQueue waiting for itself), causes my app crash

Problem

Example A: This causes the app to crash. ``` DispatchQueue.main.async { let url = URL(string: imageUrl) do { let data = try Data(contentsOf: url!) DispatchQueue.main.sync { self.imageIcon.image = UIImage(data: data) } } ``` Example B: But this doesn't ``` DispatchQueue.global().async { let url = URL(string: imageUrl) do { let data = try Data(contentsOf: url!) DispatchQueue.main.sync { self.imageIcon.image = UIImage(data: data) } } ``` As per my knowledge: - x.sync means doing thing in main thread/UI thread. - x.async means doing in background thread. - Global means performing something with concurrent queue i.e Parallel task. Question 1: Why does my app crash when I perform a task on the background thread, i.e main.async, and than call main thread to update UI? Question 2: Is there any difference between `main.async` & `global().async`?

Original source

Related problems