Skip to content

Commit 852aa9b

Browse files
Hapteinpre-commit-ci[bot]
authored andcommitted
fix: avoid premature garbage collection of tasks (#2510)
* 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>
1 parent 5fc0b30 commit 852aa9b

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

discord/client.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,9 @@ def __init__(
256256
VoiceClient.warn_nacl = False
257257
_log.warning("PyNaCl is not installed, voice will NOT be supported")
258258

259+
# Used to hard-reference tasks so they don't get garbage collected (discarded with done_callbacks)
260+
self._tasks = set()
261+
259262
async def __aenter__(self) -> Client:
260263
loop = asyncio.get_running_loop()
261264
self.loop = loop
@@ -423,8 +426,12 @@ def _schedule_event(
423426
**kwargs: Any,
424427
) -> asyncio.Task:
425428
wrapped = self._run_event(coro, event_name, *args, **kwargs)
426-
# Schedules the task
427-
return asyncio.create_task(wrapped, name=f"pycord: {event_name}")
429+
430+
# Schedule task and store in set to avoid task garbage collection
431+
task = asyncio.create_task(wrapped, name=f"pycord: {event_name}")
432+
self._tasks.add(task)
433+
task.add_done_callback(self._tasks.discard)
434+
return task
428435

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

0 commit comments

Comments
 (0)