Skip to content

Commit 8edd30f

Browse files
rrooggiieerrbdraco
andauthored
Prevent tasks from being prematurely garbage collected (#8)
Co-authored-by: J. Nick Koston <[email protected]>
1 parent 9314f85 commit 8edd30f

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

serial_asyncio_fast/__init__.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import os
2020
import urllib.parse
2121
from functools import partial
22-
from typing import Any, Callable, List, Optional, Tuple, Union
22+
from typing import Any, Callable, Coroutine, List, Optional, Set, Tuple, Union
2323

2424
import serial
2525

@@ -31,6 +31,15 @@
3131
__version__ = "0.11"
3232

3333

34+
# Prevent tasks from being garbage collected.
35+
_BACKGROUND_TASKS: Set[asyncio.Task] = set()
36+
37+
def _create_background_task(coro: Coroutine) -> None:
38+
"""Create a background task that will not be garbage collected."""
39+
task = asyncio.create_task(coro)
40+
_BACKGROUND_TASKS.add(task)
41+
task.add_done_callback(_BACKGROUND_TASKS.discard)
42+
3443
class SerialTransport(asyncio.Transport):
3544
"""An asyncio transport model of a serial communication channel.
3645
@@ -429,7 +438,7 @@ def _close(self, exc: Optional[Exception] = None) -> None:
429438
self._remove_reader()
430439
if self._flushed():
431440
self._remove_writer()
432-
self._loop.create_task(self._call_connection_lost(exc))
441+
_create_background_task(self._call_connection_lost(exc))
433442

434443
def _abort(self, exc: Optional[BaseException]) -> None:
435444
"""Close the transport immediately.
@@ -443,7 +452,7 @@ def _abort(self, exc: Optional[BaseException]) -> None:
443452
self._closing = True
444453
self._remove_reader()
445454
self._remove_writer() # Pending buffered data will not be written
446-
self._loop.create_task(self._call_connection_lost(exc))
455+
_create_background_task(self._call_connection_lost(exc))
447456

448457
async def _call_connection_lost(self, exc: Optional[Exception]) -> None:
449458
"""Close the connection.

0 commit comments

Comments
 (0)