tags:

views:

81

answers:

3

I have a console application and I want it to wait till some event is raised. But it executes the code and exits:

static void Main(string[] args)
{
  var someObjectInstance = new SomeObject();
  someObjectInstance.SomeEvent += SomeEventHandler;
}

static void SomeEventHandler()
{
  //some logic
}

I want to make my application behave like Windows Application where

Application.Run(new Form1());

is called and message loop is runned.

But I don't need neither message loop nor any form. So it looks like overhead. Is there any more light-weight way to achieve my goal?

+1  A: 

Add

Console.ReadLine(); after you attach your eventhandler.

For example..

class Program
{
    static void Main(string[] args)
    {
        System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher(@"c:\", "*.txt");
        watcher.Created += new System.IO.FileSystemEventHandler(watcher_Created);
        watcher.EnableRaisingEvents = true;
        Console.ReadLine();
    }

    static void watcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        Console.WriteLine(string.Format("{0} was created at {1:hh:mm:ss}", e.FullPath, DateTime.Now));
    }
}
gbogumil
That will just cause the Console application to hang forever, unless somebody types into the Console... Not sure that's the appropriate behavior here, since it has nothing to do with waiting for an (external) event.
Reed Copsey
Great for testing... so so great for production code.
Matthew Whited
in production I would use a service for this specific example. But this does work just fine.
gbogumil
+1  A: 
Willfulwizard
This is only going to work if you have a Windows Forms message pump, which should never be in a Console application... "Application" is defined on Windows Forms applications only. Also, sleeping like this is probably not the best approach, in any case.
Reed Copsey
+5  A: 

First off, unless SomeObject is going to raise the event on a separate thread, this won't work without some form of processing in SomeObject. If it's designed that way, however, this is fairly straightforward.

A very efficient way of handling this is to just wait on a WaitHandle:

private static ManualResetEvent waitHandle = new ManualResetEvent(false);
static void Main(string[] args)
{
    var someObjectInstance = new SomeObject();
    someObjectInstance.SomeEvent += SomeEventHandler;
    waitHandle.WaitOne(); // Will block until event occurs
}

static void SomeEventHandler()
{
    //some logic
    waitHandle.Set(); // Will allow Main() to continue, exiting the program
}
Reed Copsey