【发布时间】:2014-02-09 03:31:16
【问题描述】:
[编辑] 我想澄清 NullReferenceException 不会出现在发布的代码中,但是这段代码以某种方式返回 null
我在第一次运行我的应用程序时收到 NullReferenceException,当我将列表作为属性访问时会发生这种情况。代码如下:
/// <summary>
/// Gets the list of workouts using Lazy Loading.
/// </summary>
/// <remarks>
/// This is the point of access for Workouts in this Page.
/// </remarks>
public List<WorkoutModel> Workouts
{
get
{
if (workouts == null || !workouts.Any())
{
workouts = JsonFileHelper.LoadWorkouts();
}
return workouts;
}
}
访问的JsonFileHelper代码在这里:
/// <summary>
/// Retrieves all the workouts from local storage.
/// </summary>
/// <returns>The list of workouts.</returns>
public static List<WorkoutModel> LoadWorkouts()
{
bool couldLoadFile = true;
List<WorkoutModel> workouts = new List<WorkoutModel>();
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile textFile = null;
Task<List<WorkoutModel>> t = Task<List<WorkoutModel>>.Run(() => LoadWorkoutsAsync(textFile, localFolder, couldLoadFile));
t.Wait();
workouts = t.Result;
return workouts;
}
在后台线程调用此方法:
private static async Task<List<WorkoutModel>> LoadWorkoutsAsync(StorageFile textFile, StorageFolder localFolder, bool couldLoadFile)
{
List<WorkoutModel> workouts = new List<WorkoutModel>();
if (localFolder != null)
{
try
{
textFile = await localFolder.GetFileAsync(AppResources.FileName);
}
catch (FileNotFoundException)
{
couldLoadFile = false;
}
if (couldLoadFile)
{
// Create and use a stream to the file atomically
using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
{
// Read the text stream atomically
using (DataReader textReader = new DataReader(textStream))
{
uint length = (uint)textStream.Size;
await textReader.LoadAsync(length);
string data = textReader.ReadString(length);
workouts = JsonConvert.DeserializeObject<List<WorkoutModel>>(data);
}
}
}
}
return workouts;
}
我注意到在调试时,应用程序没有崩溃 - 这让我相信同步进行时存在一些问题,因为当应用程序正常运行时它会崩溃。这是我第一次尝试异步代码,所以我可能缺少一些东西。
什么可能导致这个问题?
【问题讨论】:
-
NullReferenceException的几乎所有情况都是相同的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。
标签: c# windows-phone-8 json.net nullreferenceexception