gpt4 book ai didi

windows-8 - 如何在 Windows8 应用程序中使用 ReadTextAsync(StorageFile file) 同步获取返回值

转载 作者:行者123 更新时间:2023-12-02 02:11:53 41 4
gpt4 key购买 nike

基本上,我的代码是一个非常简单的测试,用于在 Windows 8 风格的应用程序中写入和读取文件。这里,首先将字符串“Jessie”写入dataFile.txt,然后由程序读取,从而更新xaml中Textblock的Text属性。

从 msdn 示例中,我知道 WriteTextAsync 和 ReadTextAsync 用于 Windows 8 编程中对文件的数据文件访问。然而,测试结果是WriteTextAsync函数确实起作用,而ReadTextAsync不起作用(我可以看到“Jessie”已写入dataFile.txt的真实txt文件,但变量str始终为空)。

我在网上看到过类似的问题,但没有一个答案对我来说有意义。许多答案都提到问题可能是 ReadTextAsync 是一个异步函数,例如使用 Task 但他们的所有解决方案都不适用于我的代码。我的问题是如何使用 ReadTextAsync 同步获取返回值,或者是否有任何其他方法可以从 Windows8 应用程序中的 txt 文件中读取数据,以便我可以同步更新 UI?

代码如下:

public sealed partial class MainPage : Page
{
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

public MainPage()
{
this.InitializeComponent();

Write();
Read();
}

async void Write()
{
StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt", Windows.Storage.
CreationCollisionOption.ReplaceExisting);

await FileIO.WriteTextAsync(sampleFile, "Jessie");
}

async void Read()
{
try
{
StorageFile sampleFile = await localFolder.GetFileAsync("dataFile.txt");
string str = await FileIO.ReadTextAsync(sampleFile);

Text.DataContext = new Test(str, 1);
}
catch (FileNotFoundException)
{

}
}

public class Test
{
public Test() { }

public Test(string name, int age)
{
Name = name;
Age = age;
}

public string Name { get; set; }
public int Age { get; set; }

// Overriding the ToString method
public override string ToString()
{
return "Name: " + Name + "\r\nAge: " + Age;
}
}
}

非常感谢。

最佳答案

您应该尽可能让您的async 方法返回Task 而不是void。你可以找到我的 intro to async/await post有帮助。我还有一篇关于 asynchronous constructors 的博文.

构造函数不能是async,但您可以从构造函数启动异步过程:

public MainPage()
{
this.InitializeComponent();
Initialization = InitializeAsync();
}

private async Task InitializeAsync()
{
await Write();
await Read();
}

public Task Initialization { get; private set; }

async Task Write() { ... }
async Task Read() { ... }

关于windows-8 - 如何在 Windows8 应用程序中使用 ReadTextAsync(StorageFile file) 同步获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12362553/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com