Handle the unhandled exception in Window Service C#

Sometimes window service crash due to unhandled exception occur in the code. Which cause service to be on halt without any error log and we are unable to restart or stop the service in the windows.

In .net framework 4.5, Microsoft provides a method to handle the exception in the async event handler.

Simply write the below code snippet in the Start method of your window service and it’s done.

TaskScheduler.UnobservedTaskException += (object exSender, UnobservedTaskExceptionEventArgs eventArgs) =>
                {
                    eventArgs.SetObserved();
                    ((AggregateException)eventArgs.Exception).Handle(ex =>
                    {
                        if (logger != null)
                            logger.Error("UnobservedTaskException occured: ", ex);

                        return true;
                    });
                };
Share the joy
  •  
  •  
  •  
  •  
  •  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.