Skip to content

Commit

Permalink
fix: avoid premature garbage collection of tasks (#2510)
Browse files Browse the repository at this point in the history
* avoid premature garbage collection of Client tasks

* style(pre-commit): auto fixes from pre-commit.com hooks

* remove typehint (pre-commit makes it non compatible with older python)

* style(pre-commit): auto fixes from pre-commit.com hooks

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
Haptein and pre-commit-ci[bot] authored Jul 31, 2024
1 parent ed64942 commit 58d2cde
Showing 1 changed file with 9 additions and 2 deletions.
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

0 comments on commit 58d2cde

Please sign in to comment.