看來我不能在異步方法中拋出異常: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 并打印錯誤,但為什么控制臺忽略了異常?它沒有顯示在錯誤部分,我檢查過我會從那里錯過它。我怎樣才能得到打印的例外?
3 回答

天涯盡頭無女友
TA貢獻1831條經驗 獲得超9個贊
需要進行修復才能使其正常工作。神奇的是您需要等到 ReadAndThrow 完成。我還建議閱讀https://learn.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
}

泛舟湖上清波郎朗
TA貢獻1818條經驗 獲得超3個贊
您需要await通過修改方法的簽名來使用您的Start()方法
async Task Start()
{
await ReadAndThrow(null);
}
- 3 回答
- 0 關注
- 160 瀏覽
添加回答
舉報
0/150
提交
取消