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?
The sole difference is that a console application always spawns a console if it isn't started from one (or the console is actively suppressed on startup). A windows application, on the other hand, does not spawn a console. It can still attach to an existant console or create a new one using AllocConsole .
If you do not know what I am talking about: press Win+R, type “help” and press ENTER. A black console window will open, execute the HELP command and close again. Often, this is not desired. Instead, the command should execute without any visible window.
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With