我的应用程序是Windows Forms .NET 4 C#TCP/IP服务器。它每天都会崩溃,并且每天都会发生一次通用Windows Server崩溃消息(按关闭关闭此应用程序)。我插入了以下代码来捕获可能导致此问题的任何异常,并且我将一个简单的null对象插入一个定期调用的例程中以生成测试异常。C#未处理的异常处理程序,试图写入日志文件
两件事情:
- 当测试异常发生时,日志代码被击中在调试器中,在文件被创建并写入,和一切都很好。
- 没有调试器,我得到一个“继续或退出” .NET堆栈跟踪信息,并且无论哪个我选择,是永远不会创建或写入文件。
的.NET消息对我没用。我需要崩溃的日志文件堆栈跟踪。有谁知道我该怎么做?谢谢。
static class Program
{
[STAThread]
static void Main(string[] rgszArgs)
{
//My exception handler
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CatchUnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain(rgszArgs));
}
static void CatchUnhandledException
(object sender, UnhandledExceptionEventArgs e)
{
StreamWriter sw;
DateTime dtLogFileCreated = DateTime.Now;
Exception ex;
try
{
sw = new StreamWriter("crash-" + dtLogFileCreated.Day + dtLogFileCreated.Month
+ dtLogFileCreated.Year + "-" + dtLogFileCreated.Second
+ dtLogFileCreated.Minute + dtLogFileCreated.Hour + ".txt");
ex = (Exception)e.ExceptionObject;
sw.WriteLine("### Server Crash ###");
sw.WriteLine(ex.Message + ex.StackTrace);
sw.Close();
}
finally
{
Application.Exit();
}
}
}
只是nitpicky,但我会抛出你的streamwriter.close()调用到终端或使用SW内的使用块。 – 2011-04-19 01:20:08