From 99dd8592c0d9a82e0bdc86ed903acab609591f82 Mon Sep 17 00:00:00 2001 From: Philippe Weidmann Date: Mon, 11 Sep 2023 11:23:15 +0200 Subject: [PATCH] fix: TolerantDispatchGroup --- MailCore/Cache/BackgroundExecutor.swift | 2 +- MailCore/Utils/TolerantDispatchGroup.swift | 49 ++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 MailCore/Utils/TolerantDispatchGroup.swift diff --git a/MailCore/Cache/BackgroundExecutor.swift b/MailCore/Cache/BackgroundExecutor.swift index 9617b4e15..9876660ff 100644 --- a/MailCore/Cache/BackgroundExecutor.swift +++ b/MailCore/Cache/BackgroundExecutor.swift @@ -26,7 +26,7 @@ enum BackgroundExecutor { let taskName = "executeWithBackgroundTask \(UUID().uuidString)" DDLogDebug("Starting task \(taskName)") let processInfos = ProcessInfo() - let group = DispatchGroup() + let group = TolerantDispatchGroup() group.enter() processInfos.performExpiringActivity(withReason: taskName) { expired in if expired { diff --git a/MailCore/Utils/TolerantDispatchGroup.swift b/MailCore/Utils/TolerantDispatchGroup.swift new file mode 100644 index 000000000..a1b859e61 --- /dev/null +++ b/MailCore/Utils/TolerantDispatchGroup.swift @@ -0,0 +1,49 @@ +/* + Infomaniak Mail - iOS App + Copyright (C) 2022 Infomaniak Network SA + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ + +import CocoaLumberjackSwift +import Foundation + +public class TolerantDispatchGroup { + private let syncQueue = DispatchQueue(label: "com.infomaniak.TolerantDispatchGroup") + private let dispatchGroup = DispatchGroup() + private var callBalancer = 0 + + public func enter() { + syncQueue.sync { + dispatchGroup.enter() + callBalancer += 1 + } + } + + public func leave() { + syncQueue.sync { + guard callBalancer > 0 else { + DDLogWarn("TolerantDispatchGroup: Unbalanced call to leave()") + return + } + + dispatchGroup.leave() + callBalancer -= 0 + } + } + + public func wait() { + dispatchGroup.wait() + } +}