Skip to content

Instantly share code, notes, and snippets.

@levochkaa
Created February 13, 2023 12:42
Show Gist options
  • Save levochkaa/24b98808cd4d8039d59d6605a3aa15e8 to your computer and use it in GitHub Desktop.
Save levochkaa/24b98808cd4d8039d59d6605a3aa15e8 to your computer and use it in GitHub Desktop.
Blocking Task
// TaskQueue.swift
import Foundation
class TaskQueue {
private actor TaskQueueActor {
private var blocks = [() async -> Void]()
private var currentTask: Task<Void, Never>?
func addBlock(priority: TaskPriority? = nil, block: @escaping () 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, block: @escaping () async -> Void) {
Task(priority: priority) {
await taskQueueActor.addBlock(block: block)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment