[英]No exception in Async method
看来我无法在异步方法中引发异常:
void Start ()
{
ReadAndThrow(null);
}
public static async Task ReadAndThrow(string path)
{
if(string.IsNullOrEmpty(path) == true)
{
Debug.Log("Wrong");
throw new Exception("Wrong");
}
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
{
string line = null;
while ((line = await reader.ReadLineAsync()) != null) { }
}
}
}
这样,我可以看到调试信息,但不会在控制台中显示异常。 它确实会停止应用程序,基本上会发生异常,但不会在控制台中打印出来。
我可以使用try catch并打印错误,但是为什么控制台中会忽略该异常? 它没有显示在错误部分,我检查是否会从那里错过它。
如何获得例外打印?
编辑:
最新使用的代码,不打印:
async Task Start()
{
await ReadAndThrow(null);
}
async Task ReadAndThrow(string path)
{
Debug.Log("Start");
try
{
if (string.IsNullOrEmpty(path) == true) { Debug.Log("Wrong"); throw new Exception("Wrong in"); }
}catch(Exception e)
{
Debug.Log("Method" + e.Message);
throw;
}
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
{
string line = null;
while ((line = await reader.ReadLineAsync()) != null)
{
}
}
}
}
ReadAndThrow
将在打印异常之前完成。 需要awai
它。
您需要通过修改Start()
方法的签名来await
您的方法
async Task Start()
{
await ReadAndThrow(null);
}
需要进行修复才能使其正常工作。 魔术是您需要等待ReadAndThrow完成。 我也建议阅读https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/
public Task StartAsync ()
{
return ReadAndThrow(null); //and await StartAsync method
//or
await ReadAndThrow(); // do not forget to make method async
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.