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,
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.
In simple terms, I conclude that -
DispatchQueue.main.async
- ( ), , .
DispatchQueue.global(). async global(). sync
, global(). globalQueue mainQueue, .
MainQueue (main.sync), MainQueue, , DeadLock (MainQueue ),
main, main.sync . , main - , , , .
main
main.sync
, , main.sync, , main , main.sync.
, <26 > , sync , sync - (DispatchQueue) ,
sync
DispatchQueue
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.
Source: https://habr.com/ru/post/1687449/More articles:Why can this Kotlin object inherit from itself? - kotlinCannot get property "kotlinOutputDir" on null object - Kotlin and Spock - androidПоказать строку поиска с действием (позиция бара) - iosScript shell problem called with PHP - command-lineDocker container Hyperledger Fabric CLI - hyperledgerIf-Else Strings - javaCapturing a pointer to a TextView tab in an action bar? - androidEntity Framework query syntax for SQL Server 2017 database - c #Combining two Python dictionaries in a dictionary with the same key - pythonWhy doesn't my kera / tensor stream use GPUs - kerasAll Articles