c# - 从本地存储读取数据时出现 NullReferenceException

标签 c# windows-phone-8 json.net nullreferenceexception

[edit] 我想澄清一下,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;
}

我注意到在调试时,应用程序不会崩溃 - 这让我相信同步存在一些问题,因为它在应用程序正常运行时崩溃。这是我第一次涉足异步代码,所以我可能遗漏了一些东西。

是什么导致了这个问题?

最佳答案

请阅读 John Saunders 的问题。你需要这些知识,你应该在发帖之前已经找到了。

代码需要在所有路径上使用可预测设置的变量进行重组。如果您按原样出现此类错误,这并不奇怪。

除 FileNotFoundException 之外的异常将使 couldLoadFile 保留为 true 并将 textFile 保留为 null,从而触发此错误。这可能是你的错误。

如果这还不够,请提供堆栈跟踪。

关于c# - 从本地存储读取数据时出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21225935/

相关文章:

javascript - localStorage 不适用于 IE 10 抛出错误

c# - 如何重现不常见的 404?

testing - Windows Phone 8设备仅用于测试

c# - 无法在 NUnit 中加载程序集

c# - WebAPI 的 WPF 客户端 - 如何处理身份验证密码

c# - 以编程方式创建 Blob 存储容器

c# - 在 C# 中等效的 java 转换

c# - 防止单个控件的 Xamarin.Forms 母版页滑出

c# - 为一个键反序列化具有多种数据类型的 JSON 文件

c# - 如何使 ShouldSerialize*() 仅适用于 XML 而不是 JSON 序列化?