代码持续抛出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 theDownloadDocumentMLtask threw an exception, accessingt.Resultwill trigger anAggregateException—sometimes IDEs misreport this as a null reference.t.Result.Document: TheDocumentproperty on your returned result could be null.t.Result.Document.DocumentData: IfDocumentDatais null, callingEncoding.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

