howmanysmall/Janitor

Cancelling a thread from within itself will error.

christopher-buss opened this issue · 0 comments

A minimum example can be seen here:

const janitor = new Janitor();
janitor.Add(task.delay(1, () => janitor.Destroy()));

@rbxts.janitor.src:612: invalid argument #1 to 'cancel' (thread expected, got nil).

This is because we task.defer the thread cancel, but by this point Object is no longer valid. This could be fixed by checking if Object is still valid before we try to cancel it.

if not Cancelled then
    task.defer(function()
        task.cancel(Object)
    end)
end

My use case here is a thread that I want to end after X amount of time, but I also wish to have the ability to cancel the thread early by name of an event from another place. I want to be able to clear up both the task.delay and the event connection to end this thread early, but the thread will not necessarily be cleaned up early.