【问题标题】:How to read multiple files using "getfileasync" method in UWP如何在 UWP 中使用“getfileasync”方法读取多个文件
【发布时间】:2018-08-30 15:17:23
【问题描述】:

我正在开发一个 UWP 应用程序,我需要读取一些 Json 文件以了解资产文件夹中的数据使用情况。

然后我创建了这个方法,

public async Task<StorageFile> access(string filename)
    {
        var storageFile = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\data\" + filename);
        return storageFile;
    }

public async Task<string> read(StorageFile storagefile)
    {
        string content = await FileIO.ReadTextAsync(storagefile);
        return content;
    }

因此,我在mainpage中使用了这个方法,先读取一个文件,

Task<StorageFile> stream1_1 = access("mycourse.json");
Task<string> stream1_2 = read(stream1_1.Result);
string mycourseinfo = stream1_2.Result;

当我尝试在文本块中显示它时它成功了

mytextblock.text = mycourseinfo;

然后我添加了另一个来读取第二个文件

Task<StorageFile> stream2_1 = access("class_info.json");
Task<string> stream2_2 = read(stream2_1.Result);
string allclassinfo = stream2_2.Result;

然后问题就出来了,应用程序不会编译也没有显示错误消息,我还以为是解锁.....

我尝试单独读取第二个文件并再次成功! 那么我该如何解决这个问题!!我需要读入三个文件!

【问题讨论】:

    标签: c# asynchronous file-io uwp


    【解决方案1】:

    您只需要在方法后面添加等待,因为它们正在返回任务。当我在它后面添加等待时,它将完成执行该行,并且只有在完成后它才会移动到下一个代码行,你的死锁正在被创建,因为你没有使用等待。使用以下代码读取每个文件。

    StorageFile stream1_1 = await access("mycourse.json");
    string stream1_2 = read(stream1_1);
    string mycourseinfo = stream1_2;
    

    还要注意在使用 await 时返回类型不应该是 Task

    为了避免使您的构造函数异步,您必须使用 Loaded 事件。

    所以在页面的构造函数中添加如下加载的事件:

    Loaded += async (s, e) =>
    {
        //do any awaited stuff here
    };
    

    【讨论】:

    • 感谢您的回答!一旦我向其中添加了await,ide 要求我将 main 方法转到async。但是,我在页面加载时实现了这个方法,所以它驻留在public mainpage 内,然后我面临将主页方法变为异步的问题.....
    • 你不需要主构造器是asyc,就像你说的你可以把它放在加载的事件中并使加载的事件成为asyc @Zheng​​span>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多