Reputation: 25302
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 a Windows application where
Application.Run(new Form1());
is called and the message loop is run.
But I don't need neither a message loop nor any form. So it looks like overhead. Is there a more light-weight way to achieve my goal?
Upvotes: 13
Views: 12068
Reputation: 5409
EDIT: Sadly, I was incorrect and this won't work, because Application
is not defined for a console application (Thank you, Reed Copsey).
This should do the trick, although depending on the sleeptime you choose you could end up hogging the CPU. I feel like there must be a safer way to do this?
while (true)
{
Application.DoEvents();
Thread.Sleep(this.SleepTime);
}
Upvotes: -1
Reputation: 1923
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));
}
}
Upvotes: 3
Reputation: 564413
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
}
Upvotes: 24