Python Asyncio任务取消 [英] Python Asyncio Task Cancellation

查看:129
本文介绍了Python Asyncio任务取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读asyncio文档以了解任务取消,并且遇到了-

I was reading asyncio documentation for task cancel and I came across this -

要取消正在运行的Task,请使用cancel()方法.调用它将导致Task向包装的协程中抛出CancelledError异常.如果协程在取消过程中等待Future对象,则Future对象将被取消.

To cancel a running Task use the cancel() method. Calling it will cause the Task to throw a CancelledError exception into the wrapped coroutine. If a coroutine is awaiting on a Future object during cancellation, the Future object will be cancelled.

cancelled()可用于检查任务是否已取消.如果包装的协程没有抑制CancelledError异常并确实被取消,则该方法返回True.

cancelled() can be used to check if the Task was cancelled. The method returns True if the wrapped coroutine did not suppress the CancelledError exception and was actually cancelled.

我在这里有几个问题-

  • 包装的协程是否被称为cancel的协程?让我们在这里举个例子-

  • Is wrapped coroutine the coroutine in which cancel is called? Let's take an example here -

async def wrapped_coroutine():
    for task in asyncio.Task.all_tasks():
        task.cancel()

那么 wrapped_coroutine()是包装好的协程,任务将在该协程中抛出异常?

So wrapped_coroutine() is the wrapped coroutine where task will throw an exception?

何时将引发此异常?在哪里?

When will this exception be thrown? And where?

抑制异常在这里意味着什么?这是否意味着-

What does suppress the exception mean here? Does it mean this -

async def wrapped_coroutine():
    for task in asyncio.Task.all_tasks():
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            print("Task cancelled")

如果没有,请提供一个示例来说明如何抑制此异常.

If not, please provide an example on how to suppress this exception.

还有一个不相关的(与取消任务有关),当我取消这些任务时如何从这些任务中检索异常,所以我看不到-

And an unrelated(it's related to cancelling tasks), how do I retrieve exceptions out of these tasks when I'm cancelling these so I don't see this -

Task exception was never retrieved future:

是在 task.cancel()之前还是在 await任务之前的 try 中(在上面的示例中)?

Is it before task.cancel() or in try before await task (in the above example) ?

推荐答案

查看文档

回答您的问题:

  • "Is the wrapped coroutine the coroutine in which cancel is called?"
    No, the wrapped coroutine here is cancel_me(); .cancel() is called in main().
  • "When will this exception be thrown? And where?"
    This exception is thrown after task.cancel() is called. It is thrown inside the coroutine, where it is caught in the example, and it is then re-raised to be thrown and caught in the awaiting routine.
  • "What does suppress the exception mean here?"
    If cancel_me() would not have re-raised the exception after catching it. As the documentation of cancelled() states: "The Task is cancelled when the cancellation was requested with cancel() and the wrapped coroutine propagated the CancelledError exception thrown into it." https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancelled

这篇关于Python Asyncio任务取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆