c# - 即使捕获到异常,是否有任何方法可以找到 .net 应用程序崩溃的原因
问题描述
我有 .net 应用程序,它在登录后 ping 特定端口。我已经在 try catch 中包围了逻辑,并在我的日志中捕获了 System.net.webException。但在某些 Windows 机器中,这会导致应用程序随机崩溃。
Error Message: WebException
Exception Type: System.Net.WebException
Error Location : Unable to connect to the remote server
InnerException: System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 127.0.0.1:9000
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
StackTrace: at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at tpsyncagent.MainWindow.<ConnectToTally>d__36.MoveNext() in C:\code\tpdesktopsyncagent\MainWindow.xaml.cs:line 247
这是代码片段
try
{
Stream dataStream = TallyRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
catch(Exception e)
{
//logging code
}
解决方案
如果您遇到随机崩溃,请尝试在您的 App 类中放置一个包罗万象的异常处理程序:
protected override void OnStartup(StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
... etc ...
然后在该处理程序中转储异常的消息、内部异常和 StackTrace 以查看它被抛出的位置。在这种特殊情况下,您知道这是一个 SocketException,因此您也可以将异常转换为该异常并检查其 SocketErrorCode 属性以获取更多信息。
推荐阅读
- c# - 如何使用我的数组方法使用深度克隆?
- gatsby - 运行任何 gatsby 命令显示“-bash: gatsby: command not found”
- flutter - FlutterDriver 问题,无法通过 Key 找到 Widget
- python - 如何在另一个任务旁边运行 tkinter 的 after event?
- c++ - 是否可以在 win32 或 MFC 应用程序中从 Windows 获取“磁盘空间不足”通知?
- c# - DotNetCore3.0 WPF - error - Project file is incomplete. Expected imports are missing
- ruby-on-rails - 参数未提交
- python - pickle.load() 给出错误“初始化字符串太小”
- git - 处理功能分支,提交代码但由于测试失败而从未推送。在本地删除存储库,重新克隆存储库
- css - sass-loader 不生成 CSS