3

基本上,我的代码是一个非常简单的测试,用于在 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;
        }
    }
}

非常感谢。

4

1 回答 1

2

You should have your async methods return Task rather than void whenever possible. You may find my intro to async/await post helpful. I also have a blog post on asynchronous constructors.

Constructors cannot be async, but you can start an asynchronous process from a constructor:

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() { ... }
于 2012-09-11T04:32:10.853 回答