简体   繁体   English

调用时,异步方法不会返回

[英]Async method won't return when called

I'm having a bad time with this. 我对此感到非常糟糕。 I'm trying to make a async method that returns the contents of a local file as 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 the execution reaches the end of my method, the application waits forever. 不幸的是,在执行到达我的方法结束后,应用程序将永远等待。 It hangs completely. 它完全挂起。 It's being called at the very beginning, when the splash screen still shows (Windows Phone 8.1) 一开始就调用它,当时启动画面仍然显示(Windows Phone 8.1)

What do I miss? 我错过了什么?

I suspect that further up your call stack, your code has a call to Task.Wait or Task<T>.Result . 我怀疑你的调用堆栈会更进一步,你的代码会调用Task.WaitTask<T>.Result This can cause a deadlock that I describe on my blog . 这可能导致我在博客上描述死锁

In summary, what happens is that when await is used on a task, by default it will capture the current "context" and use that context to resume the async method. 总之,当await用于任务时,默认情况下它将捕获当前的“上下文”并使用该上下文来恢复async方法。 In this case, the context is the UI context, which is associated with the single UI thread. 在这种情况下,上下文是UI上下文,它与单个UI线程相关联。 If code further up the call stack is calling Wait or Result , then it's blocking the UI thread, which prevents the async method from finishing. 如果调用堆栈中的代码进一步调用WaitResult ,那么它将阻止UI线程,这会阻止async方法完成。

Your method is working as it should. 你的方法正常运作。 I suspect that you are encountering this issue while debugging. 我怀疑你在调试时遇到了这个问题。

I also have noticed (sometimes) such a behaviour when debugging asyc method ( here is a link to the question) - the program never returns from the method and just hangs - I don't know the exact reason of this. 我也注意到(有时)调试asyc方法时的这种行为( 这里是问题的链接 ) - 程序永远不会从方法返回而只是挂起 - 我不知道确切的原因。 To test it just try to run your method like this - for example upon 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've tested on device - it should work, but if I set a breakpoint inside your method - it will hang. 正如我在设备上测试过 - 它应该可以工作,但如果我在你的方法中设置一个断点 - 它会挂起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM