CKTIS / Python
asyncio.shield
Chráni úlohu pred zrušením odovzdaným cez obal.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
await asyncio.shield(aw)Chráni úlohu pred zrušením odovzdaným cez obal.
Volajúci stále dostane CancelledError a pôvodná úloha pokračuje. Priame zrušenie úlohy zasiahne aj obal. Zachovajte silný odkaz na úlohu.
V príklade je outer zrušený, ale otvorenie brány dá True bez zrušenia task.
import asyncio
async def main():
e = asyncio.Event()
t = asyncio.create_task(e.wait())
s = asyncio.shield(t)
s.cancel()
try:
await s
except asyncio.CancelledError:
assert not t.cancelled()
e.set()
assert await t is True
asyncio.run(main())
Príklady
import asyncio
async def main():
gate = asyncio.Event()
task = asyncio.create_task(gate.wait())
outer = asyncio.shield(task)
outer.cancel()
gate.set()
print(outer.cancelled(), await task, task.cancelled())
asyncio.run(main())
Výsledok
True True False
V príklade je outer zrušený, ale otvorenie brány dá True bez zrušenia task.