我的應用程序是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