首页 > 解决方案 > 即使捕获到异常,是否有任何方法可以找到 .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
}

标签: c#.netwpfexceptioncrash

解决方案


如果您遇到随机崩溃,请尝试在您的 App 类中放置一个包罗万象的异常处理程序:

protected override void OnStartup(StartupEventArgs e)
{
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    ... etc ...

然后在该处理程序中转储异常的消息、内部异常和 StackTrace 以查看它被抛出的位置。在这种特殊情况下,您知道这是一个 SocketException,因此您也可以将异常转换为该异常并检查其 SocketErrorCode 属性以获取更多信息。


推荐阅读