async_timeout.timeout 对比 asyncio.wait_for
async_timeout.timeout vs asyncio.wait_for
之前我用asyncio.wait_for
来控制超时,效果很好。最近学习aiohttp包,发现用asyncio_timeout.timeout
代替了超时控制。然后我阅读了 asyncio_timeout 的 github 页 (https://github.com/aio-libs/async-timeout)。作者声称它运行速度比asyncio.wait_for
快。所以我有两个问题:
asyncio_timeout.timeout
可以完全替代asyncio.wait_for
吗?我应该更换所有 asyncio.wait_for
以提高速度吗?我正在编写一个 websocket 客户端,asyncio.wait_for
当前控制着 websocket.recv
,它经常被调用。
- 在"Usage example"部分(https://github.com/aio-libs/async-timeout),似乎
asyncio_timeout.timeout
应该和async with
一起使用。但是在 aiohttp 帮助页面中,他们使用 with
而不是 async with
(http://aiohttp.readthedocs.io/en/stable/)。那么哪一个是正确的?
asyncio_timeout.timeout
比 asyncio.wait_for
快,正确。
wait_for
创建一个新任务。这对于应用程序代码可能无关紧要,但对于库来说就足够了。例如 asyncpg
尝试使用 wait_for
但为了速度被拒绝了。
asyncio_timeout
可以在除tornado.web.RequestHandler.get
等任何地方使用。Tornado仍然不支持取消任务,我希望它能在tornado 5.0 中修复
- 技术上
async_timeout.timeout
适用于 async with
和 with
。人们多次对 with
声明感到困惑:在 asyncio
世界中,鼓励异步操作。这就是我添加异步上下文管理器支持并鼓励这种用法的原因。 with
出于向后兼容性的考虑,将长期支持 - 我只是不想鼓励这种语法。
之前我用asyncio.wait_for
来控制超时,效果很好。最近学习aiohttp包,发现用asyncio_timeout.timeout
代替了超时控制。然后我阅读了 asyncio_timeout 的 github 页 (https://github.com/aio-libs/async-timeout)。作者声称它运行速度比asyncio.wait_for
快。所以我有两个问题:
asyncio_timeout.timeout
可以完全替代asyncio.wait_for
吗?我应该更换所有asyncio.wait_for
以提高速度吗?我正在编写一个 websocket 客户端,asyncio.wait_for
当前控制着websocket.recv
,它经常被调用。- 在"Usage example"部分(https://github.com/aio-libs/async-timeout),似乎
asyncio_timeout.timeout
应该和async with
一起使用。但是在 aiohttp 帮助页面中,他们使用with
而不是async with
(http://aiohttp.readthedocs.io/en/stable/)。那么哪一个是正确的?
asyncio_timeout.timeout
比asyncio.wait_for
快,正确。wait_for
创建一个新任务。这对于应用程序代码可能无关紧要,但对于库来说就足够了。例如asyncpg
尝试使用wait_for
但为了速度被拒绝了。asyncio_timeout
可以在除tornado.web.RequestHandler.get
等任何地方使用。Tornado仍然不支持取消任务,我希望它能在tornado 5.0 中修复
- 技术上
async_timeout.timeout
适用于async with
和with
。人们多次对with
声明感到困惑:在asyncio
世界中,鼓励异步操作。这就是我添加异步上下文管理器支持并鼓励这种用法的原因。with
出于向后兼容性的考虑,将长期支持 - 我只是不想鼓励这种语法。