Event:Wait() And Memory Leaks

Hi, I’ve been a bit paranoid about using :Wait() due to not really knowing where it causes memory leaks. Say for example, I create an instance of an object, then in that object, a piece of code calls Player.CharacterAdded:Wait()
However, for whatever reason, no character is ever added and the event does not fire.Is that instance now stuck in memory until the Player quits? Similarly for bindable events, does the object remain in memory until the Bindable is either fired or destroyed? Is there any way to ‘disconnect’, so to speak, a :Wait() ?

2 Likes

That thread would be stuck like that in memory and retain all of its references until the script object it is used in is garbage collected or the event actually fires.

I think you answer your own question: prefer using structures of :Connect(…) in the cases that you can’t be sure that the event will actually fire, rather than sequential sections of code with :Wait() checkpoints, and then save the connection you get back from Connect, and disconnect it when you need it to be disconnected.

6 Likes
local Event = REs.OnServerEvent
Event:Connect(function()
	print(tick(),'Event')
end)
Event:Wait()
print(tick(),'Wait')

Output:
1553893980.5875 Wait
1553893980.5877 Event

You can take a look at that, it might give you ideas

This is why I setup my module with a Destroy function to resume all waiting threads.

You can however resume a thread which is using :Wait() or wait() by resuing the coroutine but I see this as a hack that will lead to unexpected results. You will not get the expected return values.

local waitTime = 5
local resumeTime = 2
local thread  = coroutine.running()

delay(resumeTime, function() coroutine.resume(thread) end)

-- wait will not have any args now unlike print(wait())

local tm = tick()
wait(waitTime) -- wait cannot be resumet twice so it will error on resume by Roblox

print("Waited", tick() - tm)

-- using events :Wait

local intVal = Instance.new("IntValue")

delay(resumeTime, function() coroutine.resume(thread) end)

local tm = tick()
intVal.Changed:Wait()

print("Event wait", tick() - tm)

Hope this helps.