File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -172,8 +172,26 @@ functions) tied to an event loop.
172172A task also maintains a list of callback functions whose importance will become
173173clear in a moment when we discuss :keyword: `await `.
174174The recommended way to create tasks is via :func: `asyncio.create_task `.
175- Creating a task automatically schedules it for execution (by adding it to the
176- event loop's to-do list, that is, collection of jobs).
175+
176+ Creating a task automatically schedules it for execution (by adding a
177+ callback to run it in the event loop's to-do list, that is, collection of jobs).
178+ It's important to be aware that the task itself is not added to the event loop.
179+ This matters if the task object you created is garbage collected before it's
180+ called by the event loop.
181+ For example, consider this program::
182+
183+ async def hello():
184+ print("hello!")
185+
186+ async def main():
187+ hello_task = asyncio.create_task(hello())
188+ return
189+
190+ asyncio.run(main())
191+
192+ Because the coroutine ``main() `` exits before awaiting the task and no other
193+ references to the task are made, the task object ``hello_task `` *might * be
194+ garbage collected before the event loop invokes it.
177195
178196Since there's only one event loop (in each thread), :mod: `!asyncio ` takes care of
179197associating the task with the event loop for you. As such, there's no need
You can’t perform that action at this time.
0 commit comments