3

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?

2
  • 1
    where is it that you expect might throw? is it in the event subscription? or do you expect EventLogMonitor might throw? Commented Dec 14, 2011 at 16:04
  • I don't think you would get an exception trying to attach a method to the EntryWritten event. So the catch block may never fire. If you want to catch any exception that could happen in your code you can wrap the try block around the entire method/code area. so inside the EventLogMonitor method for example... This is not best practice at all btw. Commented Dec 14, 2011 at 16:07

1 Answer 1

6

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
     }

}
Sign up to request clarification or add additional context in comments.

1 Comment

Because exceptions do not propogate across threads, you probably also want a way of passing the caught exception to your main thread. The main thread can then log it/rethrow it/display it etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.