基本上,我的代码是一个非常简单的测试,用于在 Windows 8 风格的应用程序中写入和读取文件。这里,首先将字符串“Jessie”写入dataFile.txt,然后由程序读取它,以便更新xaml中Textblock的Text属性。
从msdn示例中,我知道WriteTextAsync和ReadTextAsync用于Windows 8编程中的dataFile对文件的访问。但是,测试结果是 WriteTextAsync 函数实际上可以工作,而 ReadTextAsync 则不能(我可以看到“Jessie”已写入 dataFile.txt 的真实 txt 文件,但变量 str 始终为 null)。
我在互联网上看到过类似的问题,但它们的答案对我来说都没有意义。许多答案提到问题可能是 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
只要有可能。你可能会发现我的异步/等待帖子简介 http://nitoprograms.blogspot.com/2012/02/async-and-await.html有帮助。我还有一篇博客文章异步构造函数 http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html.
构造函数不能是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() { ... }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)