Python: Fix event loop terminating too early when the main coro finishes

This commit is contained in:
Simon Hausmann 2025-09-19 10:47:45 +02:00 committed by Simon Hausmann
parent 797f8f6469
commit a159c15edd
2 changed files with 23 additions and 3 deletions

View file

@ -465,9 +465,9 @@ def run_event_loop(
global quit_event
loop = typing.cast(SlintEventLoop, asyncio.get_event_loop())
tasks: typing.List[asyncio.Task[typing.Any]] = [
asyncio.ensure_future(quit_event.wait(), loop=loop)
]
quit_task = asyncio.ensure_future(quit_event.wait(), loop=loop)
tasks: typing.List[asyncio.Task[typing.Any]] = [quit_task]
main_task = None
if main_coro:
@ -478,6 +478,8 @@ def run_event_loop(
if main_task is not None and main_task in done:
main_task.result() # propagate exception if thrown
if quit_task in pending:
await quit_event.wait()
global quit_event
quit_event = asyncio.Event()

View file

@ -12,6 +12,7 @@ import threading
import pytest
import sys
import platform
from datetime import timedelta
def test_async_basic() -> None:
@ -181,6 +182,23 @@ def test_loop_close_while_main_future_runs() -> None:
pytest.fail("Should not throw a run-time error")
def test_loop_continues_when_main_coro_finished() -> None:
async def quit_later(quit_event: asyncio.Event) -> None:
await quit_event.wait()
slint.quit_event_loop()
async def simple(quit_event: asyncio.Event) -> None:
loop = asyncio.get_event_loop()
loop.create_task(quit_later(quit_event))
quit_event = asyncio.Event()
slint.Timer.single_shot(
duration=timedelta(milliseconds=100), callback=lambda: quit_event.set()
)
slint.run_event_loop(simple(quit_event))
assert quit_event.is_set()
@pytest.mark.skipif(platform.system() == "Windows", reason="pipes aren't supported yet")
def test_subprocess() -> None:
async def launch_process(exception_check: typing.List[Exception]) -> None: