Swift3 GCD中的main.async vs main.sync()vs global().async [英] main.async vs main.sync() vs global().async in Swift3 GCD

查看:230
本文介绍了Swift3 GCD中的main.async vs main.sync()vs global().async的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例A:-这会导致应用崩溃.

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)
                }
            }

示例B:-但这不是

DispatchQueue.global().async {  
        let url = URL(string: imageUrl)
        do {
            let data = try Data(contentsOf: url!)
                DispatchQueue.main.sync {
                    self.imageIcon.image = UIImage(data: data)
                }
            }

据我所知

  • x.sync意味着在主线程/UI线程中执行操作,而x.async意味着 在后台线程中做.
  • 全局意味着对并发队列执行某些操作,即并行 任务.
  • 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:-为什么当我在后台线程(即main.async)中执行任务而不是调用主线程来更新UI时,我的应用程序崩溃了?

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:-main.async&中是否有任何区别? global().async.

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

推荐答案

简单地说,我得出的结论是-

In simple term i come to conclusion that -

  • 队列-队列有3种类型,即1种主队列,4种全局队列和任意数量的自定义队列.
  • 线程-一种是主线程,其他是后台线程 提供给我们.
  • 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

-这意味着使用后台线程(不阻止UI)在主队列中执行任务,并且在任务完成时自动更新为UI,因为它已经在Main Queue中.

-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和global().sync

这意味着使用后台线程在Global Queue中执行任务,当任务完成时,使用 global().sync 会将工作从 globalQueue移到mainQueue ,从而进行更新到用户界面.

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.

我的应用崩溃的原因

我试图通过使用(main.sync)将完成的任务带到MainQueue,但是它已经在MainQueue上,因为我没有切换队列,并且此 create DeadLock (MainQueue等待自己),导致我的应用崩溃

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

这篇关于Swift3 GCD中的main.async vs main.sync()vs global().async的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆