Created
November 3, 2023 10:57
-
-
Save levochkaa/5f38d42ea74831be8c8ce8768f43a9ad to your computer and use it in GitHub Desktop.
TaskQueue
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
final class TaskQueue: Sendable { | |
private actor TaskQueueActor { | |
private var blocks = [() async -> Void]() | |
private var currentTask: Task<Void, Never>? | |
func addBlock(priority: TaskPriority? = nil, block: @escaping @Sendable () async -> Void) { | |
blocks.append(block) | |
next(priority: priority) | |
} | |
func next(priority: TaskPriority? = nil) { | |
guard currentTask == nil, !blocks.isEmpty else { return } | |
let block = blocks.removeFirst() | |
currentTask = Task(priority: priority) { | |
await block() | |
currentTask = nil | |
next(priority: priority) | |
} | |
} | |
} | |
private let taskQueueActor = TaskQueueActor() | |
func dispatch( | |
priority: TaskPriority? = nil, | |
immediately: Bool = false, | |
block: @escaping @Sendable () async -> Void | |
) { | |
Task(priority: priority) { | |
await taskQueueActor.addBlock(priority: priority, block: block) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment