异步方法中没有异常

时间:2019-03-13 08:47:54

标签: c# unity3d exception

看来我无法在异步方法中引发异常:

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)
            {

            }
        }
    }
}

3 个答案:

答案 0 :(得分:3)

ReadAndThrow将在打印异常之前完成。需要awai了。

答案 1 :(得分:0)

您需要通过修改await方法的签名来Start()方法

async Task Start()
{
    await ReadAndThrow(null);
}

答案 2 :(得分:0)

需要修复才能使其正常运行。魔术是您需要等待ReadAndThrow完成。我也建议阅读https://docs.microsoft.com/en-us/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 
}
相关问题