diff --git a/src/lib/utils/task.rs b/src/lib/utils/task.rs index 125b5c0..d2dff48 100644 --- a/src/lib/utils/task.rs +++ b/src/lib/utils/task.rs @@ -38,8 +38,13 @@ pub async fn run_registered_task( // Run the new task separately from the current one using the executor let sender = sender.clone(); let task = exec.spawn(async move { + // HACK: For deferred tasks we yield a bunch of times to try and ensure + // we run our task at the very end of the async queue, this can fail if + // the user creates a bunch of interleaved deferred and normal tasks if mode == TaskRunMode::Deferred { - yield_now().await; + for _ in 0..64 { + yield_now().await; + } } sender .send(match to_run.await { diff --git a/src/tests/task/defer.luau b/src/tests/task/defer.luau index dceb8de..83fcda4 100644 --- a/src/tests/task/defer.luau +++ b/src/tests/task/defer.luau @@ -25,18 +25,19 @@ task.wait(0.2) assert(flag2, "Defer should work with yielding (2)") -- Deferred functions should run after other spawned threads -local flag3: boolean = false +local flag3: number = 1 task.defer(function() - if flag3 == true then - flag3 = false + if flag3 == 2 then + flag3 = 3 end end) task.spawn(function() - if flag3 == false then - flag3 = true + if flag3 == 1 then + flag3 = 2 end end) -assert(not flag2, "Defer should run after spawned threads") +task.wait() +assert(flag3 == 3, "Defer should run after spawned threads") -- Varargs should get passed correctly