Skip to content

Commit 268dba3

Browse files
committed
Fix task destroyed but pending
1 parent 08863eb commit 268dba3

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

expression/core/aiotools.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
by itself.
99
"""
1010
import asyncio
11-
from asyncio import Future
11+
from asyncio import Future, Task
1212
from collections.abc import Awaitable, Callable
1313
from 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+
6167
def 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

Comments
 (0)