Dispatch group - cannot notify to main thread

后端 未结 1 1390
栀梦
栀梦 2020-12-29 08:35

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 DispatchQue

1条回答
  •  别那么骄傲
    2020-12-29 08:59

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

    0 讨论(0)
提交回复
热议问题