Sujet : Re: asyncio and tkinter
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 04. Jul 2024, 20:30:47
Autres entêtes
Organisation : Stefan Ram
Message-ID : <asyncio-20240704190556@ram.dialup.fu-berlin.de>
ram@zedat.fu-berlin.de (Stefan Ram) wrote or quoted:
def terminate_tasks( self ):
loop = asyncio.get_running_loop()
pending = asyncio.all_tasks( loop=loop )
label_tasks = []
for task in pending:
if 'app_example_task' in str( task ):
label_tasks.append( task )
task.cancel()
group = asyncio.gather( *label_tasks, return_exceptions=True )
try:
loop.run_until_complete( group )
except AssertionError:
# ignoring an assertion error on Windows I do not understand
pass
in 2023
Yeah, that assertion error! How do you shut down tasks? It seems
everywhere people tell you to call "gather" and "run_until_complete".
But I found that in this case I need to /cancel/ my task and do
nothing else (maybe because I usually want to continue running):
def terminate_tasks( self ):
# Here we're on the event loop, but not in an async method.
loop = asyncio.get_running_loop()
pending = asyncio.all_tasks( loop=loop )
label_tasks = []
# We just send cancels to the tasks we want to cancel.
# We do not want to run all tasks to an end and terminate the
# loop, so there's no need to call anything with "gather" or
# "run" here!
for task in pending:
if 'app_example_task' in str( task ):
loop.call_soon_threadsafe( task.cancel )
. I have still not understood ascyncio. So I found the above out
the hard way: trying everything until it worked!
But I got this idea: There are three cases:
A: you are in a non-async function and not on the event loop.
B: you are in an async function and on the event loop.
C: you are in a non-async function and on the event loop.
The above is case C. And to know how to do things, you sometimes
need to know which of those three cases applies!
(Later, during the execution after "terminate_tasks", my
"app_async_mainloop" still does some waiting, so this might do
something which would otherwise be done by "run_until_complete".)