简体   繁体   中英

.Net Console application run in background

I need to make my console application to run in background. And there were some tips on the internet about how to make that happen.

The quickest tip is to change the project type to Windows Application.

I tried and yes indeed it make the console windows to disappear, but there's a problem. My application use a timer to process every x seconds, hence at the end of the Main function, I put a Console.ReadLine to prevent the app to stop. But by switching the project type to Windows Form Application the Console.ReadLine doesn't stop the app from finishing anymore.

So I have to use a windows 32 API function called ShowWindow() to hide the console window.

My question is, if I stick to the option changing project type to Windows Form Application , what do I need to keep it alive?

Don't use a timer, create a Windows Service application .
Please, do not use ShowWindow , Console.ReadLine() , WinForms etc. - it all sounds like a terrible application design.

By writing a simple class like this:

public class MyService : ServiceBase
{
    private readonly TimeSpan TimerInterval = TimeSpan.FromSeconds(5); // 'x' seconds here
    private Timer _timer; // System.Threading.Timer

    protected override void OnStart(string[] args)
    {
        _timer = new Timer(TimerCallback, null, TimeSpan.Zero, TimerInterval);
    }

    private void TimerCallback(object state)
    {
        // do whatever you want here,
        // process your requests etc.

        // this method will fire every x seconds while service is running
    }

    protected override void OnStop()
    {
        _timer.Dispose();
    }
}

you will have a Windows Service application which:

  • can easily be installed, disabled, started / restarted / stopped
  • can be configured to automatically recover after failure
  • can be run as a different user or even local system account
  • runs in background, even when no user is logged in
  • runs infinitely, by itself, without using Console.ReadLine() or Thread.Sleep
  • has no GUI \\ console window, without using a ShowWindow crutch

This is exactly what Windows Services were designed for.

well, you can use https://github.com/Topshelf/Topshelf and this allows to run it both as a console app and a windows service. A windows service is really the ideal way to do what you want, however debugging windows service is a pain. Topshelf simplifies this by letting you run and debug as a console app, then when ready, it lets you, via the command line, self register your app as a service.

however, you can just go Thread.Sleep(Timeout.Infinite)

or set up an event that needs to be triggered and wait on the event, that way your code can exit if it wants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM