
本文详解 Task exception was never retrieved 和 RuntimeError: ... is bound to a different event loop 的根本原因——在循环中重复调用 asyncio.run() 导致队列跨事件循环复用,并提供符合 asyncio 最佳实践的修复方案。
本文详解 `task exception was never retrieved` 和 `runtimeerror: ... is bound to a different event loop` 的根本原因——在循环中重复调用 `asyncio.run()` 导致队列跨事件循环复用,并提供符合 asyncio 最佳实践的修复方案。
你的代码中出现两个关键异常:
-
Task exception was never retrieved:表示某个asyncio.Task抛出了未被捕获的异常(如consumer_algoritm中因队列绑定失效而崩溃),但该任务未被await或通过task.exception()主动检查; -
bound to a different event loop:核心错误,源于在while True循环中反复调用asyncio.run(main1())—— 每次asyncio.run()都会创建全新的事件循环(Event Loop),而你在循环外创建的queue = asyncio.Queue(1)实例却始终被复用。由于asyncio.Queue在初始化时会绑定到当前活跃的事件循环,当后续asyncio.run()启动新循环后,该队列仍试图在旧循环上下文中运行(例如que_.get()内部调用self._get_loop().create_future()),从而触发RuntimeError。
✅ 正确做法:单事件循环 + 结构化并发
应将整个异步逻辑置于单次 asyncio.run() 调用内,避免循环重启事件循环。同时,使用 asyncio.create_task() 启动长期运行的协程,并通过 asyncio.gather() 或显式 await 管理生命周期:
import asyncio
import websockets
import json
import datetime
# 假设这些函数已正确定义(如 USDT_balance, candleTelo 等)
# coin, timeframe, volume 已在作用域中
async def TickersChannel_ws(timeframe_):
url = "wss://ws.okx.com:8443/ws/v5/business"
async with websockets.connect(url) as ws:
subs = {
"op": "subscribe",
"args": [
{"channel": f"mark-price-candle{timeframe_}m", "instId": "SOL-USDT-SWAP"}
]
}
await ws.send(json.dumps(subs))
async for msg in ws:
data = json.loads(msg)
if "event" not in data:
yield data.get("data", [{}])[0][0] if data.get("data") else None
async def producer(que_: asyncio.Queue):
async for ticker in TickersChannel_ws(timeframe):
try:
await que_.put(ticker)
except asyncio.QueueFull:
# 可选:丢弃旧数据或等待
pass
await asyncio.sleep(0.1)
async def consumer_algoritm(que_: asyncio.Queue, coin_: str, volume_: float):
global ts
while True:
try:
ts_ = await que_.get()
if ts_ is not None and ts != ts_:
ts = ts_
que_.task_done() # 标记任务完成(若需 join 等待)
except Exception as e:
print(f"[Consumer Error] {e}")
await asyncio.sleep(0.1)
# ✅ 主入口:单次 run,统一事件循环
async def main():
print(f'Начали в = {datetime.datetime.today().strftime("%Y-%m-%d-%H.%M.%S")}, стартовый баланс = {USDT_balance()}')
print("----------------------------------------")
cancel_order(get_list_order()[1], coin)
queue = asyncio.Queue(maxsize=1) # 在事件循环内创建
ts = candleTelo(coin, timeframe)
# 并发启动生产者与消费者
task1 = asyncio.create_task(producer(queue))
task2 = asyncio.create_task(consumer_algoritm(queue, coin, volume))
# 等待两者完成(或使用 try/except 处理异常退出)
await asyncio.gather(task1, task2, return_exceptions=True)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\nЗавершено пользователем.")
except Exception as e:
print(f"Критическая ошибка: {e}")⚠️ 关键注意事项
-
禁止在循环中调用
asyncio.run():它是为顶层入口设计的“事件循环启动器”,每次调用都会销毁前一个循环并新建,导致所有依赖循环的对象(Queue,Task,TimerHandle等)失效。 -
队列必须在
asyncio.run()内部创建:确保其与当前运行的事件循环严格绑定。 -
异常处理要显式:使用
asyncio.gather(..., return_exceptions=True)或分别await task并检查task.exception(),避免Task exception was never retrieved。 -
资源清理建议:WebSocket 连接、数据库连接等应使用
async with或在finally块中关闭;长期运行服务建议配合asyncio.Event或信号处理实现优雅退出。
遵循以上结构,即可彻底解决跨事件循环绑定问题,并构建健壮、可维护的 asyncio 应用。

















