Coroutines vs Task for a roundsystem

Currently my round system runs in a loop wrapped in a task.spawn() however, I need more control, Eg, being able to cancel a gamemode/ stop the loop. Which library could be better for this? (coroutine vs task)

I think Coroutines would be better because you can (cancel, yield, close, etc…)

Both libraries can cancel threads.

1 Like

Both are ok, i prefer coroutines over task lib when it comes to threads

Both are good picks, I’ve read that typically coroutines run faster (very negligeable).
coroutine.close
task.cancel

Correct me if I’m wrong but coroutines can pause but task cannot?

They’re both the same thing. You can spawn a coroutine with the task library then close it with the coroutine library

honestly, won’t make much of a difference

local thread = task.spawn(function()
    print("thread ran!")
    coroutine.yield()
    print("thread resumed!")
end)

local thread2 = task.delay(0.1, function()
    print("this won't run")
end)

task.spawn(thread)
task.cancel(thread2)

and

local thread = coroutine.create(function()
    print("thread ran!")
    coroutine.yield()
    print("thread resumed!")
end)
coroutine.resume(thread)

local thread2 = coroutine.create(function()
    task.wait(0.1)
    print("this won't run")
end)
coroutine.resume(thread2)

coroutine.resume(thread)
coroutine.close(thread2)

would look almost the exact same in game, and unless you’re doing tons upon tons of threads a frame, you probably won’t see too much difference (i stacked like 200 task.spawns per frame and still got 0 frame drops, likely won’t see noticable difference)

i have heard coroutines are a tad bit better memory-wise but i’m have 0 proof, +task.spawned threads are easier to debug in case of errors

nah, coroutine.yield works on task.spawn’d threads

for most cases, you should be able to use coroutine.resume(thread) and task.spawn(thread) interchangably

same with coroutine.close / task.cancel and coroutine.wrap(function)(arguments) / coroutine.resume(coroutine.create(function), arguments) / task.spawn(function, arguments)

coroutines are more complicated in nature. The task library is designed for the Roblox environment and is more lightweight when it comes to simple tasks such as canceling and delaying threads.

creating threads is expensive in both libraries, but unlike coroutine you can’t reuse threads using the task library.

You should use the task library for resuming, canceling or delaying threads.
You should use coroutine for resuming and yielding.

You should consider using both libraries for long rounds. Long rounds will mostly likely benefit from the control coroutines give.

2 Likes