[英]Python Asyncio Task Cancellation
我正在閱讀任務取消的異步文檔,我遇到了這個-
要取消正在運行的任務,請使用 cancel() 方法。 調用它將導致 Task 將 CancelledError 異常拋出到包裝的協程中。 如果協程在取消期間正在等待 Future object,則 Future object 將被取消。
cancelled() 可用於檢查任務是否被取消。 如果包裝的協程沒有抑制 CancelledError 異常並且實際上已被取消,則該方法返回 True。
我在這里有幾個問題-
包裹協程是調用取消的協程嗎? 我們在這里舉個例子——
async def wrapped_coroutine(): for task in asyncio.Task.all_tasks(): task.cancel()
那么wrapped_coroutine()
是任務會拋出異常的封裝協程嗎?
什么時候會拋出這個異常? 在哪里?
在這里抑制異常是什么意思? 是不是這個意思——
async def wrapped_coroutine(): for task in asyncio.Task.all_tasks(): task.cancel() try: await task except asyncio.CancelledError: print("Task cancelled")
如果不是,請提供有關如何抑制此異常的示例。
還有一個不相關的(它與取消任務有關),當我取消這些任務時如何從這些任務中檢索異常,所以我看不到這個 -
Task exception was never retrieved future:
是在task.cancel()
之前還是在await task
之前try
(在上面的示例中)?
查看文檔https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel中給出的示例中的代碼:
async def cancel_me():
print('cancel_me(): before sleep')
try:
# Wait for 1 hour
await asyncio.sleep(3600)
except asyncio.CancelledError:
print('cancel_me(): cancel sleep')
raise
finally:
print('cancel_me(): after sleep')
async def main():
# Create a "cancel_me" Task
task = asyncio.create_task(cancel_me())
# Wait for 1 second
await asyncio.sleep(1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("main(): cancel_me is cancelled now")
asyncio.run(main())
回答您的問題:
cancel_me()
; .cancel()
在main()
中調用。task.cancel()
后會引發此異常。 它被拋出到協程中,在示例中被捕獲,然后被重新引發以被拋出並在等待的例程中捕獲。cancel_me()
在捕獲異常后不會重新引發異常。 正如cancelled()
的文檔所述:“當使用 cancel() 請求取消並且包裝的協程傳播了拋出的 CancelledError 異常時,任務被取消。” https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancelled
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.