基本上,我的代码是一个非常简单的测试,用于在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。您可能会发现我的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/

10-11 13:58