I am about to develop a console application that will be required to continually run and carry out work at specific times.
My question is what is are best methods or practices to keep your application alive?
My thought were: A loop that never ends? A timer that sleeps and then jumps to routine when required (after set sleep period)?
I will be compiling the application into an exe and then running it as a service using AlwaysUp.
Regards..
Peter
Well I'm sure at some point it should stop, no?
Spawn a thread that does work, and have the main thread block on Console.ReadLine() if you want it to be runnable as a console app too.
If you really just want to pause the main thread forever, just block on a ManualResetEvent you never fire.
But, consider using a service if you can.
If your building a desktop application you'll want to have it run in the system tray. This will
If your building a server application you will want to write a windows service. This will
As someone who is primarily an IT Pro I would say that 3rd party applications that we get that run as console apps instead of windows services we put a lot of effort into keeping from being purchased. It creates a lot of work for us, and opens up significant support issues and security holes.
You can add a reference to
System.Windows.Forms
and callSystem.Windows.Forms.Application.Run()
to begin a standard application message loop. Ctrl-C will terminate the app.Another option is to use
Console.ReadKey()
to pause the app. LikeConsole.WriteLine("Press [ANY] key to quit..."); Console.ReadKey();
That's what I use in my console apps when they're just sitting there waiting for events to occur. In either case the app will continue to run and catch triggered events (like from a timer, WCF, FileWatcher, etc).
Create a Task and then Wait it.
Sending a thread to sleep: System.Threading.Thread.Sleep(10000);
Waiting for a key to be pressed: Console.WriteLine("Press any key to continue..."); Console.Read();
Code that runs continually is called a daemon and there is an article here outlining how to do what you ask. That will point you to an example of how to write a simple service here.