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

Example A: - This causes the application 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 is not

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 far as I know,

  • x.sync means doing things in the main thread / thread of the user interface and x.async means in the background thread.
  • Global means doing something with a parallel queue ie Parallel Task.

Quest1: - So why my application crashed when I completed the task in the background thread ie main.async, and then called the main thread to update the interface.

Quest2: - Is there a difference in main.async and global (). async.

+4
source share
3 answers

In simple terms, I conclude that -

  • . 3 , .. 1 , 4 .
  • . - , .

DispatchQueue.main.async

- ( ), , .

DispatchQueue.global(). async global(). sync

, global(). globalQueue mainQueue, .

MainQueue (main.sync), MainQueue, , DeadLock (MainQueue ),

+2

main, main.sync . , main - , , , .

, , main.sync, , main , main.sync.

, <26 > , sync , sync - (DispatchQueue) ,

+5

sync/async main/global.

- - (.. , // , )

Async - (.. , // , . )

, :
, :
1) ThreadA - ( , )
2) ThreadB - , .
3) ThreadMain -

Example A:
 DispatchQueue.main.async - ThreadA comes and executes this statement and puts your block in ThreadMain and proceeds (after its asynchronous) to the next steps after the block.

Now let's talk about ThreadMain, what will it do from here. Since ThreadMain received the block (represented by ThreadA), it starts to execute step by step, and suddenly it sees "DispatchQueue.main.sync" and sends the internal block to TheradMain in the same queue and saves onnnnn waitingggggg (from the moment it is synchronized). This way you make ThreadMain a dead end.

+2
source

Source: https://habr.com/ru/post/1687449/


All Articles