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

代码持续抛出Null Reference Exception,非空变量仍触发异常求助

Debugging That Mysterious Null Reference Exception

First off, let's get one thing straight: that null reference error is almost certainly not coming from byteArrays itself, even if the error message points that way. Let's break down your code and find the real culprit, plus fix some other lurking issues.

1. Pinpoint the Real Source of the Null Reference

Before assuming it's byteArrays, add debugging or a try/catch block to catch the error exactly where it happens. The most likely candidates are:

  • t.Result: If the DownloadDocumentML task threw an exception, accessing t.Result will trigger an AggregateException—sometimes IDEs misreport this as a null reference.
  • t.Result.Document: The Document property on your returned result could be null.
  • t.Result.Document.DocumentData: If DocumentData is null, calling Encoding.ASCII.GetBytes(x) will throw a null reference error immediately.

Pro tip: In Visual Studio, enable "Break on Thrown Exceptions" (Debug > Windows > Exception Settings) to stop the code right when the error occurs.

2. Fix the Obvious Issues in Your Code

Ditch the t.Wait()

The ContinueWith callback only runs after the original task (t) completes. Calling t.Wait() here is totally redundant and could even cause deadlocks if you're running in a sync context (like ASP.NET). Just delete it.

Handle Session Access Correctly

Session is tied to the original request thread. When you use ContinueWith without specifying a scheduler, the callback runs on a random ThreadPool thread—where Session might not be available (or might be null). Fix this by forcing the callback to run on the original request's sync context:

httpClient.DownloadDocumentML(req)
    .ContinueWith(t => {
        // Your callback logic here
    }, TaskScheduler.FromCurrentSynchronizationContext());

Thread Safety for byteArrays

If byteArrays is a regular List<byte[]>, calling Add() from a ThreadPool thread (without locking) can cause race conditions. Switch to a thread-safe collection like ConcurrentBag<byte[]> if multiple tasks might be adding to it.

3. Revised Code with Guard Clauses

Here's a cleaned-up version of your code with checks to prevent null references and fix the async context issue:

// Initialize byteArrays as a thread-safe collection (if needed)
var byteArrays = new ConcurrentBag<byte[]>();

httpClient.DownloadDocumentML(req)
    .ContinueWith(t => {
        // First, check if the task failed
        if (t.IsFaulted)
        {
            // Log the exception instead of ignoring it!
            var innerEx = t.Exception?.InnerException ?? t.Exception;
            // Handle the error appropriately (e.g., return an error response)
            return;
        }

        // Guard against nulls at every step
        var docResult = t.Result;
        if (docResult?.Document == null)
        {
            // Handle missing Document
            return;
        }

        var documentData = docResult.Document.DocumentData;
        if (string.IsNullOrEmpty(documentData))
        {
            // Handle empty/missing DocumentData
            return;
        }

        // Now we're safe to process the data
        byte[] arrayFile = Encoding.ASCII.GetBytes(documentData);
        byteArrays.Add(arrayFile);
        Session["multipleFiles"] = byteArrays;
        // return Json("multiple");
    }, TaskScheduler.FromCurrentSynchronizationContext());

Final Notes

Always use guard clauses (?., != null) when dealing with nested properties in async code—you can't assume every property will be populated. And never access Session from a non-request thread without explicitly capturing the sync context.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:02:47