跟踪 Windows 服务未处理异常的最佳方式

Best way to track Windows Service Unhandled Exception

我有一个 Windows 服务应用程序。该服务基本上是在特定时间将 Excel 文件复制到目录,然后读取 Excel 行,最后根据读取的行中的数据更新 SQL 服务器表。

最近有时会死机。在查看日志时,我发现它崩溃了,因为:

Application: WinCCServiceIzmit.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception.

Exception Info: System.IO.IOException

at System.IO.__Error.WinIOError(Int32, System.String)
at System.IO.FileStream.Init(System.String, System.IO.FileMode, System.IO.FileAccess, Int32, Boolean, System.IO.FileShare, Int32, System.IO.FileOptions, SECURITY_ATTRIBUTES, System.String, Boolean, Boolean, Boolean)
at System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, Int32, System.IO.FileOptions, System.String, Boolean, Boolean, Boolean)
at System.IO.StreamWriter.CreateFile(System.String, Boolean, Boolean)
at System.IO.StreamWriter..ctor(System.String, Boolean, System.Text.Encoding, Int32, Boolean)
at System.IO.StreamWriter..ctor(System.String, Boolean)
at System.IO.File.AppendText(System.String)
at WinccService.InnerOperation.WriteToFile(System.String)
at WinccService.InnerOperation.Stop()
at WinccService.WinccIzmit.start()
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()

你们知道我如何追踪问题的根源吗?应用程序的代码行太多。

谢谢。

订阅 UnhandeledException Event 或将您服务中的最高级别(可能在您从 OnStart 开始的方法中)包装到 try-catch.

通过这种方式,您可以捕获异常并将更多详细信息写入单独的日志文件以查明发生了什么。

然而,检查您的堆栈似乎错误发生在 WinccService.InnerOperation.WriteToFile() 中,它将从 WinccService.InnerOperation.Stop() 中调用。因此,研究这两种方法以及调用它们的人应该可以帮助您找到问题所在。此外,似乎此时 System.IO.StreamWriter.CreateFile() 将被调用并失败。可能的原因可能是文件名无效、文件已存在或权限问题。