import asyncio
import time
start = time.time()
class DMconvo:
async def feature():
print('hi')
async def two():
await asyncio.sleep(5)
print('hi again')
async def test():
await DMconvo.feature()
await DMconvo.two() # should run in background and wait 5 seconds
time.sleep(10) # should run while the previous script waits 5 seconds
asyncio.run(test())
print("--- %s seconds ---" % (time.time() - start))我认为代码是同步运行的,而不是异步运行的,但我不知道为什么。
发布于 2020-08-31 14:56:05
当呼叫等待时,Asyncio仍然是同步的。这意味着test()中的代码按顺序运行,DMconvo.two()等待5秒,time.sleep(10)等待10秒。总共15秒。您可以使用asyncio.gather同时运行协同例程。
import asyncio
import time
start = time.time()
class DMconvo:
async def feature():
print('hi')
async def two():
await asyncio.sleep(5)
print('hi again')
async def test():
await asyncio.gather(
DMconvo.feature(),
DMconvo.two(),
asyncio.sleep(10),
)
asyncio.run(test())
print("--- %s seconds ---" % (time.time() - start))发布于 2020-08-31 14:26:43
等待DMconvo.two() time.sleep(10) #应该运行,而前面的脚本等待5秒
本评论中的假设是不正确的。
time.sleep(10)在DMconvo.two()完成之前不会执行。
与同步执行相比,使用await的优点是事件循环可以在任务等待I/O时执行其他事情,但是在后台运行任务仍然必须显式地执行,例如使用create_task。
此外,使用time.sleep会阻塞线程,其中还运行着asyncio事件循环。要能够异步睡眠,您需要使用asyncio.sleep。
task = asyncio.create_task(DMconvo.two())
await asyncio.sleep(10)
await task同时创建和运行多个任务的一种更抽象和方便的方法是使用asyncio.gather,如answer by ThisIsHowItIs所示。
发布于 2020-08-31 14:25:36
使用等待意味着“程序将在那里等待直到此异步功能完成”。
所以,
await DMconvo.two()将等待5秒。
从这里移除等待,它将在后台运行此函数。
https://stackoverflow.com/questions/63672405
复制相似问题