-- Clean connections first to prevent any pending eventsfor index, task in pairs(tasks) do if typeof(task) == "RBXScriptConnection" then task:Disconnect() tasks[index] = nil self._labels[index] = nil endend
The Promise integration handles different promise states:
function Sweep:GivePromise(promise) -- Return immediately if promise is already resolved if not promise:IsPending() then return promise end -- Create new promise that can be tracked local newPromise = promise.resolved(promise) local id = self:GiveTask(newPromise) -- Clean up automatically when promise completes newPromise:Finally(function() self[id] = nil end) return newPromiseend
function SweepTaskUtils.interval(interval, callback) local running = true local thread = task.spawn(function() while running do callback() task.wait(interval) end end) return function() running = false task.cancel(thread) endend
-- Preferred: Single task for multiple operationssweep:GiveTask(function() cleanup1() cleanup2() cleanup3()end)-- Avoid: Multiple individual taskssweep:GiveTask(cleanup1)sweep:GiveTask(cleanup2)sweep:GiveTask(cleanup3)
Connection Management
-- Preferred: Group related connectionssweep:GiveTask(function() local conn1 = obj.Event1:Connect(handler1) local conn2 = obj.Event2:Connect(handler2) return function() conn1:Disconnect() conn2:Disconnect() endend)
Memory Optimization
-- Preferred: Clean unused tasks immediatelylocal taskId = sweep:GiveTask(heavyOperation)-- ... use the operation ...sweep[taskId] = nil -- Clean up when done
Always use task labels in debug mode to track task lifecycles and identify potential memory leaks.