【问题标题】:NullReferenceException when reading data from local storage从本地存储读取数据时出现 NullReferenceException
【发布时间】: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;
}

我注意到在调试时,应用程序没有崩溃 - 这让我相信同步进行时存在一些问题,因为当应用程序正常运行时它会崩溃。这是我第一次尝试异步代码,所以我可能缺少一些东西。

什么可能导致这个问题?

【问题讨论】:

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


【解决方案1】:

您应该尝试Task.Result,而不是使用Task.Wait

/// /// 从本地存储中检索所有锻炼。 /// /// 锻炼列表。

public static List<WorkoutModel> LoadWorkouts()
{
    bool couldLoadFile = true;
    List<WorkoutModel> workouts = new List<WorkoutModel>();

    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
    StorageFile textFile = null;

    List<WorkoutModel> workouts = Task<List<WorkoutModel>>.Run(() => LoadWorkoutsAsync(textFile, localFolder, couldLoadFile)).Result;

    return workouts;
}

【讨论】:

    【解决方案2】:

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

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

    FileNotFoundException 以外的异常将使 canLoadFile 为 true 且 textFile 为 null,从而触发此错误。这可能是你的错误。

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

    【讨论】:

    • 在我看来,问题在于 t.Result 以某种方式返回 null - 想不出等待本地存储获取文件会引发 FileNotFoundException 以外的异常的情况。
    猜你喜欢
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2021-02-23
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2022-12-14
    相关资源
    最近更新 更多