88by itself.
99"""
1010import asyncio
11- from asyncio import Future
11+ from asyncio import Future , Task
1212from collections .abc import Awaitable , Callable
1313from typing import Any , TypeVar
1414
@@ -58,6 +58,12 @@ def cancel(_: OperationCanceledError) -> None:
5858 return future
5959
6060
61+ # Tasks that are scheduled on the main event loop. The main event loop keeps a
62+ # a weak reference to the tasks, so we need to keep a strong reference to them until
63+ # they are completed.
64+ __running_tasks : set [Task [Any ]] = set ()
65+
66+
6167def start (computation : Awaitable [Any ], token : CancellationToken | None = None ) -> None :
6268 """Start computation.
6369
@@ -69,9 +75,12 @@ def start(computation: Awaitable[Any], token: CancellationToken | None = None) -
6975 """
7076
7177 async def runner () -> Any :
72- return await computation
78+ result = await computation
79+ __running_tasks .remove (task )
80+ return result
7381
7482 task = asyncio .create_task (runner ())
83+ __running_tasks .add (task )
7584
7685 def cb ():
7786 task .cancel ()
@@ -89,9 +98,12 @@ def start_immediate(computation: Awaitable[Any], token: CancellationToken | None
8998 """
9099
91100 async def runner () -> Any :
92- return await computation
101+ result = await computation
102+ __running_tasks .remove (task )
103+ return result
93104
94105 task = asyncio .create_task (runner ())
106+ __running_tasks .add (task )
95107
96108 def cb () -> None :
97109 task .cancel ()
0 commit comments