[编辑]我想澄清的是,NullReferenceException异常不张贴代码中出现,但是这个代码在某种程度上还给空的NullReferenceException从本地存储读取数据时
运行我的应用程序时,我得到一个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'的情况都是一样的。请参阅“[什么是.NET一个NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)”获得一些提示。 –