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
Create a Task and then Wait it.
class Program
{
static void Main(string[] args)
{
var processTask = Process();
processTask.Wait();
}
private static async Task Process()
{
var isNotCancelled = true;
while (isNotCancelled)
{
//Polling time here
await Task.Delay(1000);
//TODO: Do work here and listen for cancel
Console.WriteLine("I did some work...");
}
}
}
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.
While you should really be using a service for this, if you need/want to do this anyway, you can use a ManualResetEvent
to do this:
private ManualResetEvent Wait = new ManualResetEvent(false);
When you're finished 'starting' and want to just wait, you'd then do:
Wait.WaitOne();
When you want to stop and let it exit, you can then do:
Wait.Set();
A better solution would be to write a console application that does its job and quits. You can then use the Windows Task Scheduler to run it periodically.
You probably don't want to just spin in a loop needlessly consuming processor time.
Assuming you are on windows, you should have a loop that never ends with a call to WaitForSingleObject() or WaitForMultipleObjects() or MsgWaitForMultipleObjects() depending on your needs. Then have some synchronization object that wakes you up, such as a named event.
See the Win32 Synchronization documentation here. If you elaborate more on what your program needs to do, we can probably provide more specific advice.
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();