注:從別人博客借鑒過來的,純屬自學用
http://blog.sina.com.cn/s/blog_6262a50e0102wngq.html
文檔里明確指出:
Don’t directly create Task instances: use the ensure_future() function or the BaseEventLoop.create_task() method.
翻譯:不要直接創(chuàng)建 Task 實例,應該使用 ensure_future() 函數(shù)或 BaseEventLoop.create_task() 方法。
為什么呢?看 create_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.
翻譯:為了 interoperability,第三方的事件循環(huán)可以使用自己的 Task 子類。這種情況下,返回結果的類型是 Task 的子類。
那么用 ensure_future 還是 create_task 呢?先對比一下函數(shù)聲明:
asyncio.ensure_future(coro_or_future, *, loop=None)
BaseEventLoop.create_task(coro)
顯然,ensure_future 除了接受 coroutine 作為參數(shù),還接受 future 作為參數(shù)。
看 ensure_future 的代碼,會發(fā)現(xiàn) ensure_future 內(nèi)部在某些條件下會調(diào)用 create_task,綜上所述:
encure_future: 最高層的函數(shù),推薦使用!
create_task: 在確定參數(shù)是 coroutine 的情況下可以使用。
Task: 可能很多時候也可以工作,但真的沒有使用的理由!