C# Console Application - Keep it running

2019-01-23 15:56发布

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

11条回答
贪生不怕死
2楼-- · 2019-01-23 16:12

If your program is going to be continually running then you should sleep until the desired event occurs (e.g. XX seconds passes). If you just spin in a while {} loop you'll suck up CPU times.

If your program is going to always be running on a machine then you should consider making it a service so it automatically starts and stops with the machine.

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-23 16:14

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();
查看更多
戒情不戒烟
4楼-- · 2019-01-23 16:20

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.

查看更多
淡お忘
5楼-- · 2019-01-23 16:21

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.

查看更多
迷人小祖宗
6楼-- · 2019-01-23 16:26

Why don't you build your app as a service in the first place?

查看更多
登录 后发表回答