Search code examples
c#event-handlingevent-log

Stopping the monitoring of the event log


I have some code that watches the event log for entry written events and executes a handler when one of these events happens. My question is if I want to stop watching the event log for entry written events how to I do that. Here is some code:

    if (//some condition where I want to watch event log//)
    {
          eventLog.Log = eventLogToMonitor;
          eventLog.EnableRaisingEvents = true;
          eventLog.EntryWritten += new EntryWrittenEventHandler(EventLogHandler);

    }
    if (// some condition where I don't want to watch the event log anymore)
    {
         // turn off the event log monitoring
    }

So in a nutshell I guess my question is what code needs to go at // turn off the event log monitoring so that I am not monitoring the event log anymore?


Solution

  • You would just unsubscribe from the event.

    eventLog.EntryWritten -= EventLogHandler;
    

    Read more at http://msdn.microsoft.com/en-us/library/ms366768(v=vs.80).aspx