1919import os
2020import urllib .parse
2121from 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
2424import serial
2525
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+
3443class 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