Znalostní bázeCentrum zkoušek
CSČeština
Vybrat jazyk13

CKTIS / Python

asyncio.shield

Chrání úlohu před zrušením předaným přes obal.

Verze: Python 3.14; repository image, production runtime not attested

Syntaxe

await asyncio.shield(aw)

Chrání úlohu před zrušením předaným přes obal.

Volající stále dostane CancelledError a původní úloha pokračuje. Přímé zrušení úlohy zasáhne také obal. Zachovejte silný odkaz na úlohu.

V příkladu je outer zrušen, ale otevření brány dá True bez zrušení 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())

Pří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ýsledek

True True False

V příkladu je outer zrušen, ale otevření brány dá True bez zrušení task.

Zdroje