Skip to content

Commit de4474f

Browse files
committed
A couple minor priority elevation bug fixes in TaskScheduler
Fix two issue: 1. If a task’s priority got elevated, we would emit the `Elevating priority` log message repeatedly until the elevated priority is propagated to the underlying task via `withTaskPriorityChangedHandler` 2. Explicitly set the priority of `QueuedTask`, which ensures that we create the detached `resultTask` inside of it with that priority. I’m not sure if this was an actual issue but seems like a good cleanup regardless.
1 parent 84007ca commit de4474f

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

Sources/SKCore/TaskScheduler.swift

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,11 @@ public actor QueuedTask<TaskDescription: TaskDescriptionProtocol> {
182182
private let executionStateChangedCallback: (@Sendable (QueuedTask, TaskExecutionState) async -> Void)?
183183

184184
init(
185-
priority: TaskPriority? = nil,
185+
priority: TaskPriority,
186186
description: TaskDescription,
187187
executionStateChangedCallback: (@Sendable (QueuedTask, TaskExecutionState) async -> Void)?
188188
) async {
189-
self._priority = AtomicUInt8(initialValue: priority?.rawValue ?? Task.currentPriority.rawValue)
189+
self._priority = AtomicUInt8(initialValue: priority.rawValue)
190190
self.description = description
191191
self.executionStateChangedCallback = executionStateChangedCallback
192192

@@ -277,6 +277,10 @@ public actor QueuedTask<TaskDescription: TaskDescriptionProtocol> {
277277
"Elevating priority of \(self.description.forLogging) from \(self.priority.rawValue) to \(targetPriority.rawValue)"
278278
)
279279
}
280+
// Awaiting the result task from a higher-priority task will eventually update `priority` through
281+
// `withTaskPriorityChangedHandler` but that might take a while because `withTaskPriorityChangedHandler` polls.
282+
// Since we know that the priority will be elevated, set it now. That way we don't try to elevate it again.
283+
self.priority = targetPriority
280284
Task(priority: targetPriority) {
281285
await self.resultTask.value
282286
}
@@ -352,7 +356,7 @@ public actor TaskScheduler<TaskDescription: TaskDescriptionProtocol> {
352356
)? = nil
353357
) async -> QueuedTask<TaskDescription> {
354358
let queuedTask = await QueuedTask(
355-
priority: priority,
359+
priority: priority ?? Task.currentPriority,
356360
description: taskDescription,
357361
executionStateChangedCallback: executionStateChangedCallback
358362
)

0 commit comments

Comments
 (0)