Created
February 13, 2023 12:42
-
-
Save levochkaa/24b98808cd4d8039d59d6605a3aa15e8 to your computer and use it in GitHub Desktop.
Blocking Task
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
// 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