我意识到,如果循环尚不存在,get_event_loop
就会调用 new_event_loop
- 我想知道是否有 new_event_loop
的原因可能会在典型的 get_event_loop
之外或代替典型的 get_event_loop
被调用。
似乎new_event_loop
可用于:
- 单个应用程序中有多个事件循环。
- 在一个事件循环被杀死后创建一个新的事件循环。
不过,我想不出执行其中任何一个的充分理由。你们是否遇到过显式调用 new_event_loop
的用例?
最佳答案
显式事件循环创建主要用于两种情况:
- 您需要在主线程之外运行事件循环。这是医生所说的:
The default policy defines context as the current thread, and manages an event loop per thread that interacts with asyncio. If the current thread doesn’t already have an event loop associated with it, the default policy’s get_event_loop() method creates one when called from the main thread, but raises RuntimeError otherwise
- 您希望在单个应用程序中使用自定义策略(例如,支持同一应用程序针对不同平台的不同实现)。您可以阅读有关政策here .
基本上,如果您想更改默认事件循环类型,则需要策略。
关于python - `asyncio.new_event_loop` 有哪些用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59848036/