@@ -286,7 +286,11 @@ def _stop_proxy(context: Context, attr: str, loop_attr: str) -> None:
286286 except Exception :
287287 pass
288288 loop .call_soon_threadsafe (loop .stop )
289- time .sleep (0.5 )
289+ thread = getattr (proxy , "_thread" , None )
290+ if thread is not None :
291+ thread .join (timeout = 30 )
292+ else :
293+ time .sleep (0.5 )
290294 if hasattr (context , attr ):
291295 delattr (context , attr )
292296 if hasattr (context , loop_attr ):
@@ -368,10 +372,21 @@ def start_tunnel_proxy(context: Context, port: int) -> None:
368372
369373 def run_proxy () -> None :
370374 asyncio .set_event_loop (loop )
371- loop .run_until_complete (proxy .start ())
372- loop .run_forever ()
375+ try :
376+ loop .run_until_complete (proxy .start ())
377+ loop .run_forever ()
378+ finally :
379+ # Cancel leftover handler tasks so the loop can close cleanly.
380+ if pending := asyncio .all_tasks (loop ):
381+ for task in pending :
382+ task .cancel ()
383+ loop .run_until_complete (
384+ asyncio .gather (* pending , return_exceptions = True )
385+ )
386+ loop .close ()
373387
374388 thread = threading .Thread (target = run_proxy , daemon = True )
389+ proxy ._thread = thread
375390 thread .start ()
376391 time .sleep (1 )
377392
@@ -463,10 +478,21 @@ def start_interception_proxy(context: Context, port: int) -> None:
463478
464479 def run_proxy () -> None :
465480 asyncio .set_event_loop (loop )
466- loop .run_until_complete (proxy .start ())
467- loop .run_forever ()
481+ try :
482+ loop .run_until_complete (proxy .start ())
483+ loop .run_forever ()
484+ finally :
485+ # Cancel leftover handler tasks so the loop can close cleanly.
486+ if pending := asyncio .all_tasks (loop ):
487+ for task in pending :
488+ task .cancel ()
489+ loop .run_until_complete (
490+ asyncio .gather (* pending , return_exceptions = True )
491+ )
492+ loop .close ()
468493
469494 thread = threading .Thread (target = run_proxy , daemon = True )
495+ proxy ._thread = thread
470496 thread .start ()
471497 time .sleep (1 )
472498
0 commit comments