调度组崩溃,因为异步函数执行多次 [英] Dispatch group crashing because asynchronous function executes multiple time

查看:79
本文介绍了调度组崩溃,因为异步函数执行多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用调度组来等待两个异步过程完成.但是,第二个异步函数循环到我在数据库中拥有的消息数量.

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

推荐答案

自从被问到已经有一段时间了,但这是一个可能的解决方案.崩溃是因为您一次进入该组,但是却将其保留了约1000次:

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.

这篇关于调度组崩溃,因为异步函数执行多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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