You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

asgiref.sync_to_async内部异常无法及时传播的技术问题咨询

sync_to_async 与 ThreadPoolExecutor 的异常抛出时机差异

一、使用 sync_to_async 的异常表现

在异步代码中通过 sync_to_async 调用会抛出异常的同步函数时,异常不会立即输出,要等到程序退出(10秒后事件循环关闭时)才会打印堆栈信息:

import asyncio
from asgiref.sync import sync_to_async


def f():
    1 / 0


async def test():
    print('start')
    await sync_to_async(f)()
    print('stop')

asyncio.get_event_loop().create_task(test())
asyncio.get_event_loop().run_until_complete(asyncio.sleep(10))

二、使用 ThreadPoolExecutor 的异常表现

改用 ThreadPoolExecutor 实现相同逻辑时,异常会立即打印完整的堆栈跟踪:

import asyncio
from concurrent.futures.thread import ThreadPoolExecutor

def f():
    1 / 0

async def test():
    print('start')
    await asyncio.get_event_loop().run_in_executor(executor, f)
    print('stop')

executor = ThreadPoolExecutor(8)
asyncio.get_event_loop().create_task(test())
asyncio.get_event_loop().run_until_complete(asyncio.sleep(10))

测试环境

Linux系统下的Python 3.9.16和3.10.9版本

内容的提问来源于stack exchange,提问作者Taha Jahangir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:40:12