DukeOfMarmalade
DukeOfMarmalade

Reputation: 2788

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?

Upvotes: 3

Views: 230

Answers (1)

Asher
Asher

Reputation: 1867

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
     }

}

Upvotes: 6

Related Questions