2016-09-22 70 views
0

下面的代碼我正用它來調用concurrent API。不知何故這種方法返回多次。我已經測試沒有DispatchGroup,它按預期工作。幫助我找出它爲什麼多次打電話。DispatchGroup多次返回

我的代碼段:

 func makeConcurrentCallForUpdating(_ parent: Parent, 
         completionBlock: @escaping (_ success: Bool, _ error: DescriptiveErrorType?) -> Void) 
     let fetchGroup = DispatchGroup() 
     let queue = DispatchQueue.global(qos: .default) 
     let endPoints = [.email, .others ] 
     DispatchQueue.concurrentPerform(iterations: endPoints.count) { (index) in 
      let enumType = endPoints[index] 
      switch enumType { 
      case .email: 
       updateEmail(parent, fetchGroup: fetchGroup, completionBlock: completionBlock) 
      case .others: 
       update(parent, fetchGroup: fetchGroup, completionBlock: completionBlock) 
      default: 
      break 
     } 
     } 

     fetchGroup.notify(queue: queue) { 
      if self.endPoints.count > 0 { 
       completionBlock(false, error) 
      } else { 
      self.saveUpdated(parent, completionBlock: completionBlock) 
     } 
     } 
    } 

    #MARK: EMAIL CALL 
     fileprivate func updateEmail(_ parent: Parent, 
          fetchGroup: DispatchGroup, 
          completionBlock: @escaping (_ success: Bool, _ error: DescriptiveErrorType?) -> Void) { 
     fetchGroup.enter() 
     updateEmail(parent: parent) { (success, error) in 
      fetchGroup.leave() 
     } 
    } 

回答

0

您的集團將leave()在任何任務之前,所有的派遣任務需要enter()

移動你的fetchGroup.enter()DispatchQueue.concurrentPerform(...

let endPoints = [.email, .others ] 
    endPoints.forEach {_ in fetchGroup.enter()} //<- add this line 
    DispatchQueue.concurrentPerform(iterations: endPoints.count) { (index) in 

,並刪除fetchGroup.enter()在每個任務:

fileprivate func updateEmail(_ parent: Parent, 
         fetchGroup: DispatchGroup, 
         completionBlock: @escaping (_ success: Bool, _ error: DescriptiveErrorType?) -> Void) { 
    //fetchGroup.enter() //<- remove this line, in your `update(...)` as well 
    updateEmail(parent: parent) { (success, error) in 
     fetchGroup.leave() 
    } 
} 

請嘗試。

+0

這不適合我。我改變了通知方法中的隊列「fetchGroup.notify(queue:DispatchQueue.main)」,而不是「fetchGroup.notify(queue:queue)」。但是,如果.email和.other都被調用,則循環不會執行。如果我更新任何人,其工作正常。任何建議請 – venky

+0

@venky,謝謝你的報告。我會花一些時間進一步調查。 – OOPer

+0

@venky,我發現我的代碼按預期工作,但也發現你的原代碼的作品。我通過猜測填補了許多缺失的部分,所以這些部分正在影響,但是當你隱藏所有這些部分時,我不能再說了。如果您需要一些時間,請嘗試製作一個可以重現問題的最小項目,並顯示所有代碼(而不是編輯的代碼段)。 – OOPer