What's the difference between loop.create_task, asyncio.async/ensure_future and Task?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-22 05:28:28

问题


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.

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?


回答1:


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

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

create_task's raison d'etre[2]:

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

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

Edit

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.



来源:https://stackoverflow.com/questions/33980086/whats-the-difference-between-loop-create-task-asyncio-async-ensure-future-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!