BindToClose and new threads

Is it bad practice to use task.spawn (or new threads) on game:BindToClose() ?

I would say its not bad practice, I use it to clean up multiple players and save data. One thing to note though: I believe if the main thread exits, the game will end even if there are threads, so you should make the main thread wait until all the threads have finished. There is a 30s time limit, so use threads or anything else to make sure data is saved.

1 Like

Thanks for your reply! What you are saying is exactly what I did which is this:

--Example
local servers = {} --This would be filled with servers

game:BindToClose(function()
      for i, v in pairs(servers) do
           task.spawn(function()
                asyncFunctionThatYields(v)
                servers[i] = nil
           end)
      end
      --
      local beforeTime = DateTime.now().UnixTimestamp
      while GetLength(servers) > 0 and (DateTime.now().UnixTimestamp - beforeTime) < maxYield do
          task.wait()
      end
end)

This method fixes any issue, because if you don’t use new threads, you’d need to yield for every call and maybe you don’t reach to call every “server”.

If you do use new threads, the bindtoclose would finish and the server would close, being the possibility that those async calls haven’t ended.

Because I forgot to close the topic when I came up with the solution, I’ll mark yours as the solution for your time.

1 Like