@@ -245,7 +245,8 @@ async def open(self) -> None:
245245 # Close servers and clear the pools.
246246 for server in self ._servers .values ():
247247 await server .close ()
248- self ._monitor_tasks .append (server ._monitor )
248+ if not _IS_SYNC :
249+ self ._monitor_tasks .append (server ._monitor )
249250 # Reset the session pool to avoid duplicate sessions in
250251 # the child process.
251252 self ._session_pool .reset ()
@@ -298,9 +299,14 @@ async def select_servers(
298299 ]
299300
300301 if not _IS_SYNC and self ._monitor_tasks :
301- joins = [t .join () for t in self ._monitor_tasks ] # type: ignore[func-returns-value]
302- await asyncio .gather (* joins )
303- self ._monitor_tasks = []
302+ join_tasks = []
303+ try :
304+ while self ._monitor_tasks :
305+ join_tasks .append (self ._monitor_tasks .pop ())
306+ except IndexError :
307+ pass
308+ join_tasks = [t .join () for t in join_tasks ] # type: ignore[func-returns-value]
309+ await asyncio .gather (* join_tasks )
304310
305311 return servers
306312
@@ -532,7 +538,8 @@ async def _process_change(
532538 and self ._description .topology_type not in SRV_POLLING_TOPOLOGIES
533539 ):
534540 await self ._srv_monitor .close ()
535- self ._monitor_tasks .append (self ._srv_monitor )
541+ if not _IS_SYNC :
542+ self ._monitor_tasks .append (self ._srv_monitor )
536543
537544 # Clear the pool from a failed heartbeat.
538545 if reset_pool :
@@ -708,7 +715,8 @@ async def close(self) -> None:
708715 old_td = self ._description
709716 for server in self ._servers .values ():
710717 await server .close ()
711- self ._monitor_tasks .append (server ._monitor )
718+ if not _IS_SYNC :
719+ self ._monitor_tasks .append (server ._monitor )
712720
713721 # Mark all servers Unknown.
714722 self ._description = self ._description .reset ()
@@ -719,7 +727,8 @@ async def close(self) -> None:
719727 # Stop SRV polling thread.
720728 if self ._srv_monitor :
721729 await self ._srv_monitor .close ()
722- self ._monitor_tasks .append (self ._srv_monitor )
730+ if not _IS_SYNC :
731+ self ._monitor_tasks .append (self ._srv_monitor )
723732
724733 self ._opened = False
725734 self ._closed = True
@@ -959,7 +968,8 @@ async def _update_servers(self) -> None:
959968 for address , server in list (self ._servers .items ()):
960969 if not self ._description .has_server (address ):
961970 await server .close ()
962- self ._monitor_tasks .append (server ._monitor )
971+ if not _IS_SYNC :
972+ self ._monitor_tasks .append (server ._monitor )
963973 self ._servers .pop (address )
964974
965975 def _create_pool_for_server (self , address : _Address ) -> Pool :
0 commit comments