[英]Write stack trace when an exception is thrown from another thread
如何將未處理的異常(從任何線程拋出)的堆棧跟蹤寫入文件?
我需要它來幫助調試掛起的應用程序。
看一下AppDomain.UnhandledException事件。 看來這正是您所需要的。
謝謝大家,但是我已經看到,當我從Visual Studio運行程序時,當引發任何線程的未處理異常時,.NET寫入控制台窗口的跟蹤輸出不會重定向到控制台窗口。
當我運行與Visual Studio分開的程序時,它才被重定向。 因此,這段代碼非常有用,可以查看任何線程拋出的未處理異常的所有堆棧跟蹤
Trace.Listeners.Clear();
TextWriterTraceListener twtl = new TextWriterTraceListener(Path.Combine(Environment.CurrentDirectory, "logfile.txt"));
twtl.Name = "TextLogger";
twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime | TraceOptions.Callstack;
ConsoleTraceListener ctl = new ConsoleTraceListener(false);
ctl.TraceOutputOptions = TraceOptions.DateTime;
Trace.Listeners.Add(twtl);
Trace.Listeners.Add(ctl);
Trace.AutoFlush = true;
我相信您可以通過監聽AppDomain.UnhandledException事件來做到這一點。 在WPF的情況下,還值得一聽Application.Current.Dispatcher.UnhandledException
您可以通過ex.StackTrace在catch塊中獲取堆棧跟蹤,如下所示:
try
{
//Your code;
}
catch(Exception ex)
{
string innerException = ex.InnerException;
string stackTrac = ex.StackTrace;
//Write this stackTrac to any file where you want
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.