Please Add 'add_done_callback' to ASyncIO?
Please Add 'add_done_callback' to ASyncIO?
This was added in Python 3.7 and allows for ASyncIO created tasks to self clean up when needed.
asyncio: Add support to close the running loop and cancel background tasks
<!-- Thanks for submitting a Pull Request! We appreciate you spending the
time to improve MicroPython. Please provide enough information so that
others can review your Pull Request.
Before submitting, please read:
https://github.com/micropython/micropython/blob/master/CODEOFCONDUCT.md
https://github.com/micropython/micropython/wiki/ContributorGuidelines
Please check any CI failures that appear after your Pull Request is opened.
-->
Summary
<!-- Explain the reason for making this change. What problem does the pull request
solve, or what improvement does it add? Add links if relevant. -->
CPython will automatically shutdown the event loop and cancel all background async tasks when the main task exits from asyncio.run(...). This is especially important if the background tasks need to perform some sort of cleanup and/or reset.
This adds support for asyncio.all_tasks() which returns a set object similar to the way CPython works and allows inspection of all running tasks. This may be used inside a running event loop to forcibly cancel all running tasks.
Testing
<!-- Explain what testing you did, and on which boards/ports. If there are
boards or ports that you couldn't test, please mention this here as well.
If you leave this empty then your Pull Request may be closed. -->
This adds two tests in hopes of measuring compatibility with CPython. The first is asyncio_all_tasks which shows the collection of tasks returned from the asyncio.all_tasks() function. The second is asyncio_shutdown which shows the compatibility of shutting down background tasks as the main task exits for various reasons.
Trade-offs and Alternatives
<!-- If the Pull Request has some negative impact (i.e. increased code size)
then please explain why you think the trade-off improvement is worth it.
If you can think of alternative ways to do this, please explain that here too.
Delete this heading if not relevant (i.e. small fixes) -->
The spirit of this feature was originally implemented in #9870; however, it needs this concept to fully work correctly.
Micropython still suffers from the issue where a try block in the main task will not have its finally executed if it's interrupted from a KeyboardInterrupted (like eg. from mpremote); however, at least this will trigger the proper cancel and cleanup of background tasks.
As a caveat the Loop in Micropython can be reused after being close()d. In CPython, such is forbidden. CPython uses a Runner to manage the shutdown of the loop and tasks after the main task exits.