使用threading调用async协程触发coroutine未await运行警告如何解决
问题解决方法
报错原因
你定义的Start是异步协程函数,threading.Thread的target参数仅支持传入同步可调用对象,它不会自动执行协程的await逻辑,因此会抛出coroutine 'Start' was never awaited的运行时警告。
解决方案
方案1:直接使用异步逻辑(推荐,适配aiogram原生架构)
你正在使用的是异步版本的aiogram框架,本身的事件循环天然支持并发执行协程,完全不需要额外引入线程,直接在回调函数中await执行Start即可:
@dp.message_handler(state=UpdateTime.UpdateTime) async def process_name(message: types.Message, state: FSMContext): if message.text.isdigit(): await Start(bot, message) await state.finish()
该方案符合异步框架设计规范,不存在线程安全风险。
方案2:必须使用独立线程运行协程的场景
如果你确实有特殊需求要将任务放到独立线程执行,需要在线程内部单独初始化异步事件循环来运行协程:
import asyncio # 同步包装函数,用于在线程内启动事件循环执行协程 def sync_wrapper(bot, message): asyncio.run(Start(bot, message)) @dp.message_handler(state=UpdateTime.UpdateTime) async def process_name(message: types.Message, state: FSMContext): if message.text.isdigit(): th = Thread(target=sync_wrapper, args=(bot, message)) th.start() await state.finish()
注意:跨线程调用bot接口需要注意线程安全问题,如果只是需要后台执行任务不需要隔离线程,更推荐使用
asyncio.create_task(Start(bot, message))创建异步后台任务。
内容的提问来源于stack exchange,提问作者Leo
相关产品推荐
相关产品推荐

