(coroutine.wrap(function()WaitForLiveAccessCheck()Madwork.ConnectToOnClose(function()ProfileService.ServiceLocked=true local P=0 local O={}for P,Q in ipairs(AutoSaveList)do O[P]=Q end for O,Q in ipairs(O)do if Q:IsActive()==true then P=P+1;(coroutine.wrap(function()SaveProfileAsync(Q,true)P=P-1 end))()end end while P>0 or ActiveProfileLoadJobs>0 or ActiveProfileSaveJobs>0 do Madwork.HeartbeatWait()end return end,UseMockDataStore==false)end))()return ProfileService
-- Release all loaded profiles when the server is shutting down:
coroutine.wrap(function()
	WaitForLiveAccessCheck()
	Madwork.ConnectToOnClose(
		function()
			ProfileService.ServiceLocked = true
			-- 1) Release all active profiles: --
			-- Clone AutoSaveList to a new table because AutoSaveList changes when profiles are released:
			local on_close_save_job_count = 0
			local active_profiles = {}
			for index, profile in ipairs(AutoSaveList) do
				active_profiles[index] = profile
			end
			-- Release the profiles; Releasing profiles can trigger listeners that release other profiles, so check active state:
			for _, profile in ipairs(active_profiles) do
				if profile:IsActive() == true then
					on_close_save_job_count = on_close_save_job_count + 1
					coroutine.wrap(function() -- Save profile on new thread
						SaveProfileAsync(profile, true)
						on_close_save_job_count = on_close_save_job_count - 1
					end)()
				end
			end
			-- 2) Yield until all active profile jobs are finished: --
			while on_close_save_job_count > 0 or ActiveProfileLoadJobs > 0 or ActiveProfileSaveJobs > 0 do
				Madwork.HeartbeatWait()
			end
			return -- We're done!
		end,
		UseMockDataStore == false -- Always run this OnClose task if using Roblox API services
	)
end)()

return ProfileService
