Created
February 6, 2024 03:45
-
-
Save kk-vv/199bdf9205e47587ced5cc586810386b to your computer and use it in GitHub Desktop.
Convert multi async Tasks to sync queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func fetchFromRemote(by ids: [MKAssetId]) { | |
let group = DispatchGroup() | |
let queue = DispatchQueue(label: "felix.hu.remote.assets") | |
let semaphore = DispatchSemaphore(value: 1) | |
for id in ids { | |
queue.async { // queue.async still sync but new thread, if queue.sync is main thread will cause dead lock | |
group.enter() | |
semaphore.wait() | |
Task { | |
do { | |
// await action | |
let result = try await fetch(by: id) | |
group.leave() | |
semaphore.signal() | |
} catch { | |
group.leave() | |
semaphore.signal() | |
} | |
} | |
} | |
} | |
group.notify(queue: .main) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment