Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try catch to catch errors in .NET threadpool

In an application I have I register to the EventLog.EntryWritten event, and a .NET Threadpool thread is used to wait for the change event to happen. I think an exception is occurring in this .NET Threadpool thread, so I want to use try/catch to make sure, like this:

try {
eventLog.EntryWritten += new EntryWrittenEventHandler(EventLogMonitor); 
}
catch (System.Componentmodel.Win32exception e)
{
// log error
}

I am just wondering if I have my try/ catch in the right place to monitor this thread for an exception?

like image 562
DukeOfMarmalade Avatar asked Feb 18 '26 05:02

DukeOfMarmalade


1 Answers

the code you wrote will catch an exception on the registration to the event, not the event itself.

you should put the try..catch block in your EventLogMonitor method.

private void EventLogMonitor (Object sender,EntryWrittenEventArgs e)
{
     try
     { 
       // your logic goes here
     }
     catch (Exception ex)
     {
          //do something with the excpetion
     }

}
like image 85
Asher Avatar answered Feb 20 '26 17:02

Asher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!