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 1 commit
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
Next Next commit
avoid premature garbage collection of Client tasks
  • Loading branch information
Haptein committed Jul 30, 2024
commit 2a6371a27cd5f22e768a33d40bac9e62c6241eac
13 changes: 10 additions & 3 deletions discord/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import sys
import traceback
from types import TracebackType
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Generator, Sequence, TypeVar
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Generator, Sequence, Set, TypeVar

import aiohttp

Expand Down 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[asyncio.Task] = 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