Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

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

Example A:- This cause App 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 don'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 and x.async means doing in background thread.
  • Global means performing something with concurrent queue i.e Parallel task.

Quest1:- So why does my app crashed when i performed task in background thread i.e main.async and than call main thread to update UI.

Quest2:- Is there any difference in main.async & global().async.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...