Код: Выделить всё
import asyncio
async def async_operation():
while True:
await asyncio.sleep(1)
async def main():
task1 = None
task2 = None
try:
task1 = asyncio.create_task(async_operation())
task2 = asyncio.create_task(async_operation())
await asyncio.wait([task1, task2], timeout=2, return_when=asyncio.FIRST_COMPLETED)
finally:
if task1 and not task1.done():
print("Cancelling task1!") # this is printed!
task1.cancel()
if task2 and not task2.done():
task2.cancel()
try:
# This throws:
# asyncio.exceptions.InvalidStateError: Result is not set.
res = task1.result()
# I would expect one of the following two cases to be true:
#
# 1. the task completes and thus the result is set or
# 2. it is cancelled in the finally block and thus calling .result()
# should raise CancelledError and not InvalidStateError
print(f"Got result: ${res}")
except asyncio.CancelledError:
print(f"Caught CancelledError!")
asyncio.run(main())
Просматривать документацию, которую я получаю подозрительность, потому что я не планируется, что на самом деле не будет выработано. и, таким образом, это никогда не будет отменено.
Я бы приветствовал объяснение поведения, а также предложения для более идиоматической реализации.>
Подробнее здесь: https://stackoverflow.com/questions/795 ... ncelled-ta