【问题标题】:GetFileAsync freezes app and does not throws exceptionGetFileAsync 冻结应用程序并且不抛出异常
【发布时间】:2015-12-20 04:09:29
【问题描述】:

我正在尝试使用以下内容读取文件:

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
}

但是应用程序冻结了应用程序并且没有抛出任何异常。 “Console.Writeline”停在“这里?文件”中。

我做错了吗?

【问题讨论】:

  • async 关键字应该在static 之后..
  • 操作。我的错误,但不是解决方案..
  • 如果是真的,它就不会编译。

标签: c# async-await uwp


【解决方案1】:

我必须检索一个信息到一个 id 绑定的对象。我做了一些Arr = MyFile.getArray(filename).Result;里面有... JsonObject json = await read(filename);

这就是您的应用程序冻结的原因,当您调用 Task.Result 时,它实际上是死锁的。 You're blocking on async code.

相反,您还需要使整个调用链异步。这意味着调用read 的代码本身应该是async 并返回Task

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

注意 C# 方法的命名约定是帕斯卡大小写,异步方法应添加“Async”后缀。

【讨论】:

  • 感谢您的建议。我将方法更改为static async public void getArr( MyObject my) 并在异步方法中进行分配。它有效,但我不知道这是否是一项好技术。
  • @vinicius 不知道这是什么意思
【解决方案2】:

您的代码看起来不错,因此问题很可能出在调用“读取”方法的方法中。您是否可能同步调用它,例如“read(myfile.json).Result”?如果是这样,您很可能会遇到死锁。

这里有一些关于这个问题的讨论:FileIO.ReadTextAsync occasionally hangs

最好的解决方案是确保您不会尝试将异步调用与同步调用混为一谈。

【讨论】:

  • 我必须检索一个信息到一个 id 绑定的对象。我做了someArr = MyFile.getArray(filename).Result;,里面有... JsonObject json = await read(filename); ...。您能建议我另一种从文件中检索该数据的方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 2015-01-29
相关资源
最近更新 更多