WinRT: Loading Static Data Using GetFileFromApplicationUriAsync ()

I have some data in my Windows 8 application that should be sent using and only some static data. Actually: this is a simple XML file that needs to be deserialized.

Data is saved in Assets \ data.xml (Assets is the default folder from the Blank App template).

I use this piece of code to access it:

private static async Task<MyObject> Load() { if (Windows.ApplicationModel.DesignMode.DesignModeEnabled) { return new SampleData(); } var uri = new Uri("ms-appx:///Assets/data.xml"); Debug.WriteLine("Getting file from Application"); var file = await StorageFile.GetFileFromApplicationUriAsync(uri); Debug.WriteLine("Opening file for reading async"); var stream = await file.OpenStreamForReadAsync(); var serializer = new XmlSerializer(typeof(MyObject)); Debug.WriteLine("Begin deserialization"); var result = (MyObject)serializer.Deserialize(stream.AsInputStream().AsStreamForRead()); return result; } 

Call Method:

 public static MyObject GetMyObject() { if (_myObject == null) { _myObject = Load().Result; } return _myObject; } 

The "funny" part about this:

If I set a breakpoint in var uri = new Uri(...); and I use F11 to go through the code, everything works as expected. I get all the debugging lines, and my application shows static data as needed.

If I don’t set a breakpoint and go to this piece of code, I get only the output of Debug Getting a file from Application and nothing else happens. It seems that GetFileFromApplicationUriAsync() never returns. I waited more than five minutes, but nothing happened.

Does anyone have an idea?

+4
source share
1 answer

Thanks for submitting the code. Try changing the Load method as follows:

 //your code var file = await StorageFile.GetFileFromApplicationUriAsync(uri).AsTask().ConfigureAwait(false); //your code var stream = await file.OpenStreamForReadAsync().ConfigureAwait(false); //your code 

The main difference here is AsTask (). ConfigureAwait (false)

EDIT:

Nice to hear that it works. The explanation is quite simple: when you use task.Result or task.Wait() in a GUI thread in combination with the await keyword, you cause a deadlock. This is because after awaiting code resumes in the same context, it was called (in your case, the GUI thread). And since the GUI thread waiting for the task to complete (via Result or Wait() ), a deadlock occurs, and the code after the await keyword will never be called. ConfigureAwait(false) indicates that the current context can be ignored and thus allows you to complete your code. More on this here: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

+11
source

All Articles