Reputation: 33
Basiclly, my code is a very simple test for write and read files in a windows 8 style app. Here, a string "Jessie" is firstly written to dataFile.txt, and then it is read by the program so that the Text property of a Textblock in xaml could be updated.
From msdn samples, I knew that WriteTextAsync and ReadTextAsync are for dataFile access to file in Windows 8 programming. However, the test result is that WriteTextAsync function actually works whereas ReadTextAsync does not(I can see the real txt file that "Jessie" has been written to dataFile.txt, however the variable str is always null).
I have seen similar questions from internet, but none of the answers for them make sense to me. Many answer mentioned the problem might be ReadTextAsync is a async function, such like using Task but all of their solutions doen't work to my code. My question is how can I get the return value synchronously using ReadTextAsync or is there any other method to read data from txt file in Windows8 app so that I can update the UI synchronously?
Here is code:
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;
}
}
}
Thanks very much.
Upvotes: 3
Views: 2075
Reputation: 457007
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() { ... }
Upvotes: 2