uasyncio: cancel a task which is running inside a task #13431
-
Hello, To show the issue more easy I wrote a small example: import uasyncio
async def myPrinter():
global subTask
while(True):
print("== Printing now ==")
subTask = uasyncio.create_task(subPrinter())
try:
await uasyncio.wait_for(subTask, 10000)
finally:
print("Subtask finished")
print("== Printing finished ==")
async def subPrinter():
for i in range(7):
print("sub print")
await uasyncio.sleep_ms(500)
async def mainLoop():
global subTask
printerTask = uasyncio.create_task(myPrinter())
await uasyncio.sleep_ms(2000)
print("Its time to stop subPrinter...")
subTask.cancel()
print("SubPrinter is stopped")
await uasyncio.sleep_ms(10000)
print("Program is finished")
uasyncio.run(mainLoop()) So I start a Why can't I just stop the Output of the program above:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Add another async def myPrinter():
global subTask
while True:
print("== Printing now ==")
try:
subTask = uasyncio.create_task(subPrinter())
try:
await uasyncio.wait_for(subTask, 10000)
finally:
print("Subtask finished")
print("== Printing finished ==")
except uasyncio.CancelledError:
print("Subtask cancelled") On my system (using the Linux build of Micropython) I get this output:
|
Beta Was this translation helpful? Give feedback.
-
Oh, thanks for the hint. async def myPrinter():
global subTask
while(True):
print("== Printing now ==")
subTask = uasyncio.create_task(subPrinter())
try:
await uasyncio.wait_for(subTask, 10000)
except:
print("subtask exception") Due to the missing exception handling for the subTask, the Thank you for the idea. |
Beta Was this translation helpful? Give feedback.
Oh, thanks for the hint.
You are right, I forgot the except statement. It also works if I change the finally statement to an except path:
Due to the missing exception handling for the subTask, the
uasyncio.CancelledError
will affect the printerTask too. But if I handle it, the printerTask keeps running.Thank you for the idea.