Reputation: 685
I am reading a file, present in the Universal windows Application scope, from an external project added as .dll to the first one. The code seems to stuck or hang at GetFileAsync. Also when I run the same stub from the Application instead of the .dll project, it works. I need to know if there is a different way of reading a file present in Application folder from a .dll project, to be used in same project,. Code for reading the file :
private static async Task<Stream> getStreamAsync()
{
try
{
StorageFolder storageFolder = Package.Current.InstalledLocation;
StorageFile file = await storageFolder.GetFileAsync("file.json");
Stream stream = null;
if (file != null)
{
var randomAccessStream = await file.OpenReadAsync().AsTask().ConfigureAwait(false);
stream = randomAccessStream.AsStreamForRead();
}
return stream;
}
catch (Exception ex)
{ }
}
private Stream fetchStream()
{
var stream = getStreamAsync().Result;
return stream;
}
private func()
{
Stream StreamFetched = fetchStream();
}
Upvotes: 0
Views: 877
Reputation: 44066
You're deadlocking your UI thread with itself:
fetchStream
calls getStreamAsync()
.
getStreamAsync()
awaits on storageFolder.GetFileAsync, scheduling the continuation to the current synchronization context (the UI thread's message queue).
The UI thread immediately returns from getStreamAsync()
and continues executing fetchStream()
.
Executing .Result
blocks the UI thread waiting for the continuation to complete.
... BUT
The continuation will never complete because the continuation is scheduled to run later on the UI thread and the UI thread is blocked.
Try something like:
StorageFile file = await storageFolder.GetFileAsync("file.json").ConfigureAwait(false);
That will cause the continuation to be scheduled against the default synchronization context instead of the current one. This is (presumably) why you also have a ConfigureAwait(false)
further down on OpenReadAsync()
Upvotes: 6