Skip to content

Commit

Permalink
Hold references to background tasks to avoid garbage collection (Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Jan 6, 2024
1 parent 1f488b0 commit 2f07824
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/socketio/async_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
from . import exceptions
from . import packet

# this set is used to keep references to background tasks to prevent them from
# being garbage collected mid-execution. Solution taken from
# https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task
task_reference_holder = set()


class AsyncServer(base_server.BaseServer):
"""A Socket.IO server for asyncio.
Expand Down Expand Up @@ -588,8 +593,11 @@ async def _handle_event(self, eio_sid, namespace, id, data):
sid, namespace)
return
if self.async_handlers:
self.start_background_task(self._handle_event_internal, self, sid,
eio_sid, data, namespace, id)
task = self.start_background_task(
self._handle_event_internal, self, sid, eio_sid, data,
namespace, id)
task_reference_holder.add(task)
task.add_done_callback(task_reference_holder.discard)
else:
await self._handle_event_internal(self, sid, eio_sid, data,
namespace, id)
Expand Down

0 comments on commit 2f07824

Please sign in to comment.