C# – How to wait on events on a second thread

ceventsmultithreading

Consider the following code in a class called Worker

    FileSystemWatcher watcher = new FileSystemWatcher();
    public void Run()
    {
        watcher.Path = @"c:\queue";
        watcher.Created += new FileSystemEventHandler(watcher_Created);
        watcher.EnableRaisingEvents = true;
    }

Now here's what I would like to do wih the Worker, but obviouly this doesn't fly.

        Worker worker = new Worker();
        Thread thread = new Thread(worker.Run);
        thread.Start();
        Console.ReadLine(); // something else more interesting would go here.

The reason being that the Run method ends rather than going into some sort of event loop. How do I get an event loop going. (I think I"m looking for something like Application.Run)

Best Answer

Not tested, but your "event" loop, if you're wanting it to run on the thread, would look something like this:

private bool running = true;
private AutoResetEvent waiter = new AutoResetEvent(false);

public void Run()
{
    FileSystemWatcher watcher = new FileSystemWatcher("C:\\");
    FileSystemEventArgs changes = null;

    watcher.Changed +=
        (object sender, FileSystemEventArgs e) => {
            changes = e;
            waiter.Set();
        };

    watcher.EnableRaisingEvents = true;

    while (running)
    {
        waiter.WaitOne();
        if (!running) break;

        Console.WriteLine("Path: {0}, Type: {1}",
                changes.FullPath, changes.ChangeType);
    }

    Console.WriteLine("Thread complete");
}

public void Stop()
{
    running = false;
    waiter.Set();
}

You would place this code in a class and run it on a separate thread (if you wish). If you want to have your main thread wait on the thread you create finishing (although why bother creating a thread in that case?) then you can use the Thread.Join method.