Search code examples
c#event-log

Is there way to remove Thread Sleep code?


With below code snippet, I am trying to do "Subscription to Windows Event Log".

using System;
using System.Diagnostics.Eventing.Reader;

namespace ConsoleApp1
{
class Program
{
    static void Main(string[] args)
    {

        EventLogWatcher watcher = null;
        try
        {
            EventLogQuery subscriptionQuery = new EventLogQuery("Application", PathType.LogName, "*[System/EventID=101]");

            watcher = new EventLogWatcher(subscriptionQuery);

            watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(EventLogEventRead);

            // Activate the subscription
            watcher.Enabled = true;

            for (int i = 0; i < 5; i++)
            {
                // Wait for events to occur. 
                System.Threading.Thread.Sleep(10000);
            }
        }
        catch (EventLogReadingException e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            // Stop listening to events
            watcher.Enabled = false;

            if (watcher != null)
            {
                watcher.Dispose();
            }
        }

        Console.ReadKey();

    }

    private static void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg)
    {
        // Make sure there was no error reading the event.
        if (arg.EventRecord != null)
        {
            Console.WriteLine(arg.EventRecord.TimeCreated);
            Console.WriteLine(arg.EventRecord.FormatDescription());
        }
        else
        {
            Console.WriteLine("The event instance was null.");
        }
    }
}
}

Everything looks good over here, but is there any way that we can remove below thread sleep code?

for (int i = 0; i < 5; i++)
            {
                // Wait for events to occur. 
                System.Threading.Thread.Sleep(10000);
            }

What could be other solution to that can invoke event happening?


Solution

  • Anyway console will end, so you may want run until user says stop.

    So, replace the lines of sleeping codes:

      for (int i = 0; i < 5; i++)
            {
                // Wait for events to occur. 
                System.Threading.Thread.Sleep(10000);
            }
    

    With :

    Console.WriteLine("Press the Escape (Esc) key to quit: \n");
    do 
    {
        cki = Console.ReadKey();
        // nothing to do and ready to recieve next pressed key.
    } while (true);