在UWP中,我使用WriteTextAsync写入文件(20K ascii文本文件),然后使用ReadTextAsync读取同一文件。当我使用断点运行时,单步执行ReadRawTextFromFile,它可以正常工作。当我正常运行(没有断点)时,我从ReadTextAsync返回null。我没有任何例外。我该怎么做才能读取该文件。
// This is for writing the RawText
private async void WriteRawTextToFile(string fname, string textToWrite)
{
try
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile localFile = await localFolder.CreateFileAsync(fname, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(localFile, textToWrite);
}
catch(Exception e)
{
Console.WriteLine($"WriteRawTextToFile Exception: '{e}'");
}
}
private string TextFromFile; // to get back from the file read
private async void ReadRawTextFromFile(string fname, string defaultString)
{
try
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile localFile = await localFolder.GetFileAsync(fname);
TextFromFile = await FileIO.ReadTextAsync(localFile); // get Text from the file
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
TextFromFile = defaultString;
}
}
试着解释一下@HenkHolterman在评论中的含义,
没有返回类型(void)的async
和async Task
对Exception和throwable来说不太好,它们只对异步事件监听器有意义,但对async Task<T>
或async T
没有意义,它们有返回类型,如果有的话异常,然后异常将通过返回类型传递给调用者。你也可以参考here关于async和await的最佳实践
我的建议是
async
方法有返回类型,例如bool
或Task<bool>
来表明该方法是否成功地做了它的事情WriteLines()
的Console
无法输出错误等,请尝试使用Debug.WriteLines()
命名空间中的System.Diagnostics
。这可能是也可能不是关于打印到输出窗口的无异常的真正问题还试图解释@MichaelRandal的意思(同样,来自评论)
如果我可以从评论中引用关于断点的话,你已经提出了“特别声明”,因此,我们希望你详细说明,例如提供更多信息,可能是堆栈输出,断点输出等,因此任何想要回答或贡献的人都不必继续询问所需的信息