NullReferenceException从本地存储中读取数据时



[编辑]我想澄清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;
}

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

什么可能导致此问题?

请阅读约翰·桑德斯的问题。您需要此知识,并且在此处发布之前应该已经找到了。

需要在所有路径上可预测设置的变量来重组代码。如果您得到这种错误,就不足为奇了。

FilenotFoundException以外的一个例外将使CANLOADFILE如null一样为真和文本文件,从而触发此错误。这可能是您的错误。

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

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

//////从本地存储中检索所有锻炼。//////锻炼清单。

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;
}

相关内容

  • 没有找到相关文章

最新更新