Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Avoid premature garbage collection of Client tasks #2510

Merged
merged 4 commits into from
Jul 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions discord/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,9 @@ def __init__(
VoiceClient.warn_nacl = False
_log.warning("PyNaCl is not installed, voice will NOT be supported")

# Used to hard-reference tasks so they don't get garbage collected (discarded with done_callbacks)
self._tasks = set()

async def __aenter__(self) -> Client:
loop = asyncio.get_running_loop()
self.loop = loop
Expand Down Expand Up @@ -423,8 +426,12 @@ def _schedule_event(
**kwargs: Any,
) -> asyncio.Task:
wrapped = self._run_event(coro, event_name, *args, **kwargs)
# Schedules the task
return asyncio.create_task(wrapped, name=f"pycord: {event_name}")

# Schedule task and store in set to avoid task garbage collection
task = asyncio.create_task(wrapped, name=f"pycord: {event_name}")
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)
return task

def dispatch(self, event: str, *args: Any, **kwargs: Any) -> None:
_log.debug("Dispatching event %s", event)
Expand Down
Loading