Dispatch group crashing because asynchronous function executes multiple time

流过昼夜 提交于 2021-01-29 04:30:43

问题


I am trying to use dispatch groups to wait for two asynchronous processes to finish. However the second asynchronous function loops to the amount of messages I have in my database.

The code below crashes because the number of dispatch is not balanced since dispatch leave is higher than the number of dispatch enters due to the multiple executions of the second asynchronous function. Is there a different way to implement dispatch groups in this case.

dispatch_group_enter(dispatch_group)
ref.observeEventType(.ChildAdded, withBlock: {(snapshot) in
//execute once
dispatch_group_leave(self.dispatch_group)
}

dispatch_group_enter(dispatch_group)
ref.observeEventType(.ChildAdded, withBlock: {(snapshot) in
//execute 1000 times
dispatch_group_leave(self.dispatch_group)
}

dispatch_group_notify(self.dispatch_group, dispatch_get_main_queue()) {
print("done")
}

回答1:


Its been a while since this was asked, but here is a possible solution. It is crashing because you are entering the group once, but leaving it about 1000 times in:

dispatch_group_enter(dispatch_group)
ref.observeEventType(.ChildAdded, withBlock: {(snapshot) in
//execute 1000 times
dispatch_group_leave(self.dispatch_group)
}

You have to make sure, that you only leave the group as often as you´ve entered it.



来源:https://stackoverflow.com/questions/39188005/dispatch-group-crashing-because-asynchronous-function-executes-multiple-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!