MicroPython uasyncio 在微控制器和常规 Python 上的行为不同:任务只是保持 运行

MicroPython uasyncio behaves differently on micro controller and regular Python: task just keeps running

这是我的例子:

try:
    import uasyncio as asyncio
except ImportError:
    import asyncio

async def count():
    i = 0
    while True:
        print(i)
        i += 1
        await asyncio.sleep(1)

async def main():
    asyncio.create_task(count())
    await asyncio.sleep(5)

asyncio.run(main())
asyncio.run(main())

在常规 Python 中,我得到:

0
1
2
3
4
0
1
2
3
4

然而,MicroPython 产生以下输出:

0
1
2
3
4
0
5
1
6
2
7
3
8
4
9

所以第一个任务不会停止,而是在第二个任务运行期间保持运行。

我认为这是一个缺陷,我已记录问题 #7471 来跟踪它(那里也有解决方法)。感谢您通过清晰、可重现的示例报告问题!

显然,这是当前预期的行为:

By default uasyncio retains state, as discussed here. Arguably in the interests of CPython compatibility it shouldn't, but on occasion this behaviour can be useful. Currently the user has the choice of whether to allow retained state.

来源:https://github.com/micropython/micropython/issues/7471

因此,解决方法是在 asyncio.run:

的后续调用之间调用 asyncio.new_event_loop
try:
    import uasyncio as asyncio
except ImportError:
    import asyncio

async def count():
    i = 0
    while True:
        print(i)
        i += 1
        await asyncio.sleep(1)

async def main():
    asyncio.create_task(count())
    await asyncio.sleep(5)

asyncio.run(main())
asyncio.new_event_loop()
asyncio.run(main())