File tree 1 file changed +17
-2
lines changed 1 file changed +17
-2
lines changed Original file line number Diff line number Diff line change @@ -520,7 +520,10 @@ Shielding From Cancellation
520
520
521
521
The statement::
522
522
523
- res = await shield(something())
523
+ task = asyncio.create_task(something())
524
+ background_tasks.add(task)
525
+ task.add_done_callback(background_tasks.discard)
526
+ res = await shield(task)
524
527
525
528
is equivalent to::
526
529
@@ -539,11 +542,23 @@ Shielding From Cancellation
539
542
the ``shield() `` function should be combined with a try/except
540
543
clause, as follows::
541
544
545
+ task = asyncio.create_task(something())
546
+ background_tasks.add(task)
547
+ task.add_done_callback(background_tasks.discard)
542
548
try:
543
- res = await shield(something() )
549
+ res = await shield(task )
544
550
except CancelledError:
545
551
res = None
546
552
553
+ .. important ::
554
+
555
+ Save a reference to tasks passed to this function, to avoid
556
+ a task disappearing mid execution. The event loop only keeps
557
+ weak references to tasks. A task that isn't referenced elsewhere
558
+ may get garbage-collected at any time, even before it's done.
559
+ For reliable "fire-and-forget" background tasks, gather them in
560
+ a collection.
561
+
547
562
.. versionchanged :: 3.10
548
563
Removed the *loop * parameter.
549
564
You can’t perform that action at this time.
0 commit comments