loop.create_task,asyncio.async / ensure_future和Task有什么区别? [英] What's the difference between loop.create_task, asyncio.async/ensure_future and Task?

查看:731
本文介绍了loop.create_task,asyncio.async / ensure_future和Task有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对某些 asyncio 函数感到困惑。我看到有 BaseEventLoop.create_task(coro) 函数来安排协同例程。 create_task 的文档说它是一个新功能,为了兼容,我们应该使用 asyncio.async(coro) ,通过再次引用文档,我看到它是 asyncio.ensure_future(coro) 会再次安排

I'm a little bit confused by some asyncio functions. I see there is BaseEventLoop.create_task(coro) function to schedule a co-routine. The documentation for create_task says its a new function and for compatibility we should use asyncio.async(coro) which by referring to docs again I see is an alias for asyncio.ensure_future(coro) which again schedules the execution of a co-routine.

同时,我一直在使用 Task(coro) 用于安排协同程序执行,这似乎也可以正常工作。那么,所有这些之间有什么区别?

Meanwhile, I've been using Task(coro) for scheduling co-routine execution and that too seems to be working fine. so, what's the difference between all these?

推荐答案

您已经注意到,它们都做同样的事情。

As you've noticed, they all do the same thing.

asyncio.async 必须替换为 asyncio.ensure_future ,因为在Python> = 3.5中,已将 async 设为关键字 [1]

asyncio.async had to be replaced with asyncio.ensure_future because in Python >= 3.5, async has been made a keyword[1].

create_task 的存在理由 [2]

第三方事件循环可以使用其自己的Task子类来实现互操作性。在这种情况下,结果类型是Task的子类。

Third-party event loops can use their own subclass of Task for interoperability. In this case, the result type is a subclass of Task.

这也意味着您不应直接创建 Task ,因为不同的事件循环可能具有不同的创建任务的方式。

And this also means you should not create a Task directly, because different event loops might have different ways of creating a "Task".

编辑

另一个重要区别是,除了接受协程外, ensure_future 也接受任何等待的对象;另一方面, create_task 只接受协程。

Another important difference is that in addition to accepting coroutines, ensure_future also accepts any awaitable object; create_task on the other hand just accepts coroutines.

这篇关于loop.create_task,asyncio.async / ensure_future和Task有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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