调度组 - 无法通知主线程 [英] Dispatch group - cannot notify to main thread

查看:22
本文介绍了调度组 - 无法通知主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 GCD 上阅读 Swift 3 进化后,我正在尝试创建调度组.问题是 group.notify(queue: 在我将 DispatchQueue.main 作为队列传递时不通知,尽管它确实适用于后台队列.

After reading Swift 3 evolution on GCD, I am trying to create dispatch group. The problem is the group.notify(queue: do not notify when I pass DispatchQueue.main as a queue, although it does work for background queue.

此外,我不确定我的语法是否全部正确,因为我正在尝试将代码从 Swift 2 转换为 Swift 3.

Also I am not sure my syntax is all correct, as I am trying to convert code from Swift 2 to Swift 3.

typealias CallBack = (result: Bool) -> Void
func longCalculations (completion: CallBack) {

let backgroundQ = DispatchQueue.global(attributes: .qosBackground)

    let group = DispatchGroup()  
    var fill:[Int] = [] 
    for item in 0...200 {
        group.enter() 
        if item > 50 {
            fill.append(item)
        }
        group.leave() 
    }

//Below in the notify argument If I pass `backgroundQ`, it seems to work correctly but not when DispatchQueue.main is passed.

此代码无效

group.notify(queue: DispatchQueue.main, execute: {
    completion(result: true)
    })
 }

这可以正常工作

group.notify(queue: backgroundQ, execute: {
    completion(result: true)
    })
 }
_______________________________________________________

longCalculations() { print($0) }

推荐答案

在阅读 Matt 建议的帖子后,我发现我正在将任务提交到主队列,当我要求在主线程本身上获得通知时,它进入了死锁.

After reading post suggested by Matt, I found that I was submitting task to main queue and when I asked to be notified on main thread itself, it got in the deadlock.

我已经更改了代码,现在它可以按预期工作了,

I have altered the code and now it is working as intended,

typealias CallBack = (result: [Int]) -> Void
func longCalculations (completion: CallBack) {
  let backgroundQ = DispatchQueue.global(attributes: .qosDefault)
  let group = DispatchGroup()

  var fill:[Int] = []
  for number in 0..<100 {
      group.enter()
      backgroundQ.async(group: group,  execute: {  
          if number > 50 {
            fill.append(number)
          }
          group.leave()

          })
      }

     group.notify(queue: DispatchQueue.main, execute: {
       print("All Done"); completion(result: fill)
     }) 
}

longCalculations(){print($0)}

这篇关于调度组 - 无法通知主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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