Async method will not return when called

I'm having a bad time with this. I am trying to make an asynchronous method that returns the contents of a local file as a string. This is my approach:

private static async Task<string> ReadContentsAsString(string fileName)
    var uri = new Uri(string.Format(@"ms-appx:///{0}", fileName));
    var file = await StorageFile.GetFileFromApplicationUriAsync(uri).AsTask().ConfigureAwait(false);
    var stream = await file.OpenStreamForReadAsync().ConfigureAwait(false);

    using (var streamReader = new StreamReader(stream))
        return await streamReader.ReadToEndAsync();


Unfortunately, after my method finishes executing, the application waits forever. It hangs completely. It is called at the very beginning when the splash screen is still displayed (Windows Phone 8.1)

What am I missing?


source to share

2 answers

I suspect that further down your call stack, your code has a call Task.Wait

or Task<T>.Result

. This can cause a dead end, which I describe in my blog .

In general, it happens that when await

used in a task, by default it will grab the current "context" and use that context to resume the method async

. In this case, the context is a UI context that is associated with a single UI thread. If the code is even higher, the call stack calls Wait

or Result

, then it blocks the UI thread, which prevents the method from completing async




Your method works as it should. I suspect you are running into this issue while debugging.

I also noticed (sometimes) this behavior when debugging the asyc method ( here is the link to the question) - the program never returns from the method and just hangs - I don't know the exact reason for this. To test it, just try to run your method like this, for example on a button click:

private async void firstBtn_Click(object sender, RoutedEventArgs e)
    Debug.WriteLine("Before method");
    string readValue = await ReadContentsAsString("TextFile1.txt");
    Debug.WriteLine(string.Format("Read value: {0}", readValue));


As I tested on device - it should work, but if I set a breakpoint inside your method - it hangs.



All Articles