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

查看:22
本文介绍了Swift3 GCD 中的 main.async 与 main.sync() 与 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:- 但这不是

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

据我所知,

  • x.sync 表示在主线程/UI 线程中执行操作,x.async 表示在后台线程中执行.
  • 全局意味着使用并发队列执行某些操作,即并行任务.

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 & 有什么区别吗?全局().异步.

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

推荐答案

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

In simple term i come to conclusion that -

  • 队列- 队列有 3 种类型,即 1 个主队列、4 个全局队列和任意数量的自定义队列.
  • Threads- 一个是主线程和其他系统的后台线程提供给我们.
  • 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,因为它已经在主队列中.

-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().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.

我的应用程序崩溃的原因

我试图通过 using(main.sync) 将已完成的任务带到 MainQueue,但它已经在 MainQueue 上,因为我没有切换 Queue,并且这 创建 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 与 main.sync() 与 global().async的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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