vinicius
vinicius

Reputation: 73

GetFileAsync freezes app and does not throws exception

I'm trying to read a file with this:

public static async Task<JsonObject> read(string nome)
{
     nome = GetSafeFilename(nome);
     string json = "";
     try 
     {
           StorageFolder folder = ApplicationData.Current.LocalFolder; 
           Debug.WriteLine("here? folder");
           StorageFile jsonFile = await folder.GetFileAsync(nome);
           Debug.WriteLine("here? file");
           json = await FileIO.ReadTextAsync(jsonFile);
           Debug.WriteLine("here? fileio" + json);
     }
     catch ( Exception ex )
     {
           Debug.WriteLine(ex.StackTrace);
     }

     return JsonObject.Parse(json); //converte string para jsonobject
}

But the app freezes app and does not throw any exeption. The "Console.Writeline" stops in "here? file".

Am I doing something wrong?

Upvotes: 0

Views: 753

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

I have to retrieve a information to an object that id binding. I did someArr = MyFile.getArray(filename).Result; and inside it has ... JsonObject json = await read(filename);

That's why your app freezes, it actually deadlocks when you call Task.Result. You're blocking on async code.

Instead, you need to make your entire call chain async as well. This means that whichever code calls read should itself be async and return a Task:

public async Task ReadJsonAsync()
{
     var jsonObject = await MyFile.ReadAsync("foo");
}

Note C# naming conventions for methods are pascal case, and async methods should be added the "Async" postfix.

Upvotes: 2

Mikael Koskinen
Mikael Koskinen

Reputation: 12906

Your code looks fine so the issue is quite likely in the method which calls the "read" method. Are you perhaps calling it synchronously, for example "read(myfile.json).Result? If so, you're quite likely encountering a deadlock.

Here's some discussion about the issue: FileIO.ReadTextAsync occasionally hangs

The best solution is to make sure that the you're not trying to mix async with synchronous calls.

Upvotes: 0

Related Questions