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

间歇性System.ArgumentNullException异常排查求助

间歇性System.ArgumentNullException异常排查求助

大家好,我最近碰到个特别头疼的间歇性问题:运行代码时会时不时在指定位置抛出System.ArgumentNullException,翻来覆去查了好久都没找到根因,想请各位大佬帮忙分析下。

相关代码片段

首先是触发异常的核心调用代码(已精简掉无关部分):

endpoints.MapGet("/sse/workorder", async Task (HttpContext context, CancellationToken token) => {
    while (!token.IsCancellationRequested)
    {
        await context.SSESendEventAsync(new SSEEvent(), token);
        await Task.Delay(TimeSpan.FromSeconds(2), token);
    }
}

public static async Task SSESendEventAsync(this HttpContext ctx, SSEEvent e, CancellationToken token)
{
    ArgumentNullException.ThrowIfNull(ctx);
    ArgumentNullException.ThrowIfNull(e);

    if (!string.IsNullOrWhiteSpace(e.Id))
    {
        await ctx.Response.WriteAsync($"id: {e.Id}\n", token);   // <- 异常就发生在这一行
    }
    // 其他逻辑代码省略...
}

另外还有一段在程序其他位置持续异步运行的代码,我怀疑可能和这个问题有关,也贴出来供大家参考:

try
{
    while (!token.IsCancellationRequested)
    {
        await ctx.Response.WriteAsync(": \n\n", token);

        await Task.Delay(TimeSpan.FromSeconds(...), token);
        // 后续代码省略...
    }
}
catch
{
    // 异常捕获逻辑省略...
}

我现在特别困惑的点是:明明已经在SSESendEventAsync方法开头就检查了ctx不为null,但写Response的时候还是会抛出ArgumentNullException,而且这个问题不是每次都触发,间歇性发作,实在摸不着头绪。有没有朋友遇到过类似的情况?或者能给我一些排查的方向建议?

备注:内容来源于stack exchange,提问作者Isius

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 14:12:58