In one of my C# Windows Forms Applications I had a problem whereby a third-party component was throwing an exception in another thread. The exception wasn’t causing any problems but it wasn’t being handled by anything.
Basically I wanted to catch the exception, log it for reference and possible future investigation, and then ignore it and carry on.
I started by adding event handlers to the exception events:
1 2 3 |
Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; |
And then I added log4net to simply log the error and move on (added via NuGet Package Manager)
So my app.config had the following added:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> </configSections> <log4net> <root> <level value="DEBUG" /> <appender-ref ref="LogFileAppender" /> </root> <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" > <param name="File" value="C:\WebRotator\log.txt" /> <param name="AppendToFile" value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd hh:mm:ss} - %-5p - %m%n" /> </layout> </appender> </log4net> |
And my main Program.cs ended up looking like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
static class Program { public static readonly ILog Logger = LogManager.GetLogger(typeof(Program)); [STAThread] static void Main() { XmlConfigurator.Configure(); Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmRotator()); } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { LogException("CurrentDomain_UnhandledException", (Exception)e.ExceptionObject); } static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { LogException("Application_ThreadException", e.Exception); } private static void LogException(string exceptionArea, Exception e) { Logger.ErrorFormat("{0}: {1}", exceptionArea, e); } } |
Job done!