异步创建任务未运行函数



使用asyncio,我试图生成一个任务,以阻止我的主事件循环被套接字侦听器阻塞。但是,异步创建任务函数从未运行过。代码运行是因为print("Game Loop")语句已运行,但client_socket()函数代码从未发出。

async def main_loop(self):
self.queue = asyncio.Queue()
loop = asyncio.get_event_loop().create_task(self.client_socket())
while True:
print("Game Loop")
async def client_socket(self):
print("Client socket online")
reader, writer = await asyncio.open_connection(host="127.0.0.1", port="55555")
writer.write("CONNECT".encode("utf-8"))
while True:
data = await reader.read(1024)
if not data:
continue

由于您的声明print("Game Loop")已经运行,我们假设您正在运行以下或类似的内容:

asyncio.run(main_loop())

函数client_socket永远无法运行,因为它从未被等待过。CCD_ 5不产生对事件循环的控制。

为了确保client_socketGame Loop的第一次输出后运行,您可以awaitit:

while True:
print("Game Loop")
await loop

但是,如果不希望等待client_socket,则任何其他await表达式都将产生对事件循环的控制。例如:

while True:
print("Game Loop")
await asyncio.sleep(1)

最新更新