asyncio: Add support to close the running loop and cancel background tasks #15715
+258
−4
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
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 aset
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
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 theasyncio.all_tasks()
function. The second isasyncio_shutdown
which shows the compatibility of shutting down background tasks as the main task exits for various reasons.Trade-offs and Alternatives
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 itsfinally
executed if it's interrupted from a KeyboardInterrupted (like eg. frommpremote
); 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 aRunner
to manage the shutdown of the loop and tasks after the main task exits.