如何使用DispatchGroup在for循环中进行异步调用

编程入门 行业动态 更新时间:2024-10-25 06:26:53
本文介绍了如何使用DispatchGroup在for循环中进行异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在下面的示例代码中,我在失败时调用 complete(false).但是,由于我使用 DispatchGroup 对象来确保所有异步请求均已完成,因此我不能仅在失败时调用 syncGroup.leave(),因为notify 将被调用,其中包含 complete(true),使该函数在应返回 false 的情况下返回 true 失败.

In my example code below, I call complete(false) on failure. However, since I'm using a DispatchGroup object to make sure all asynchronous requests are complete, I cannot just call syncGroup.leave() on failure, as the notify will be called, which contains complete(true), making this function return true, when it should be returning false for failure.

我是否纠正无法正确完成我的功能的情况下不调用 syncGroup.leave()的问题?还是应该调用 syncGroup.leave()并以某种方式尝试确定结果是什么,以便在失败时返回 false ?

Am I correct in not calling syncGroup.leave() on failure to complete my function correctly? Or should I be calling syncGroup.leave() and somehow trying to determine what the result is, so I can return false on failure?

let syncGroup = DispatchGroup() syncGroup.enter() for track in unsynced { register(time: time, withCompletion: { (success: Bool) -> () in if success { self.debug.log(tag: "SyncController", content: "Registered") syncGroup.leave() } else { complete(false) } }) } //all requests complete syncGroup.notify(queue: .main) { self.debug.log(tag: "SyncController", content: "Finished registering") complete(true) }

推荐答案

您必须在for循环中输入该组.您可能要引入一个附加的错误标志.

You have to enter the group within your for loop. You might want to introduce an additional error flag.

示例实现:

var fail = false let syncGroup = DispatchGroup() for track in unsynced { syncGroup.enter() register(time: time, withCompletion: { (success: Bool) -> () in if success { self.debug.log(tag: "SyncController", content: "Registered") syncGroup.leave() } else { fail = true syncGroup.leave() } }) } //all requests complete syncGroup.notify(queue: .main) { if fail { complete(false) } else { self.debug.log(tag: "SyncController", content: "Finished registering") complete(true) } }

更多推荐

如何使用DispatchGroup在for循环中进行异步调用

本文发布于:2023-11-23 10:30:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621115.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   DispatchGroup

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!