Skip to content

Instantly share code, notes, and snippets.

@levochkaa
Created November 3, 2023 10:57
Show Gist options
  • Save levochkaa/5f38d42ea74831be8c8ce8768f43a9ad to your computer and use it in GitHub Desktop.
Save levochkaa/5f38d42ea74831be8c8ce8768f43a9ad to your computer and use it in GitHub Desktop.
TaskQueue
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