How to Run a .Net Console Application in the Background

How to run a .NET console application in the background

Easy!

It seems hard to believe, but it works as a charm. I have used this for some setup projects, when you want to perform custom tasks with no signs of it.

  • Create the project as a Windows application project (this is the hard part).
  • Never make calls to any form. Just keep on in exactly as in your console application

    class Program
    {
    static void Main(string[] args)
    {
    // Just don't call Application.Run(new frmMain(args));

    // ... your code
    }
    }

This is because windows application projects are no really different than console, except because of the first form and references.
It is totally hidden execution. Try it!

.Net Console application run in background

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.

Can I use BackgroundService in dot net core console application

Yes, just be sure to keep the main thread alive so the application does not exit.

This article seems to explain the process decently;
https://medium.com/@daniel.sagita/backgroundservice-for-a-long-running-work-3debe8f8d25b

And here's an SO that shows the process aswell:

Trigger background service ExecuteAsync method in .Net core console application

Also if you want to do some background processing, take a look at hangfire:

https://www.hangfire.io/

Which can also be ran from a windows service.

Have tasks permanently run in background in Console application

Take a look at Timer class. You can specify the period in its constructor and it will call specified method periodically.

Edit: Code sample below

static void Main(string[] args)
{
Timer timer1 = new Timer(1000)
{
Enabled = true,
AutoReset = true
};

Timer timer2 = new Timer(2000)
{
Enabled = true,
AutoReset = true
};

Timer timer3 = new Timer(3000)
{
Enabled = true,
AutoReset = true
};

timer1.Elapsed += async (sender, e) => await HandleTimer("Timer1");
timer2.Elapsed += async (sender, e) => await HandleTimer("Timer2");
timer3.Elapsed += async (sender, e) => await HandleTimer("Timer3");

Console.ReadLine();
}

private static async Task HandleTimer(string message)
{
Console.WriteLine(message);
}

How to run Console Application in Background (no UI)?

Set on your Project in "Application" the Output Type to "Windows Application".



Related Topics



Leave a reply



Submit