Skip to content

Instantly share code, notes, and snippets.

@AlbertoDePena
Created March 8, 2019 21:41
Show Gist options
  • Save AlbertoDePena/a460af58011dfe8e5dba1e5706095f94 to your computer and use it in GitHub Desktop.
Save AlbertoDePena/a460af58011dfe8e5dba1e5706095f94 to your computer and use it in GitHub Desktop.
Gracefully exit dotnet console app in docker container
using System;
using System.Threading;
using System.Threading.Tasks;
namespace GracefulExit
{
class Program
{
// AutoResetEvent to signal when to exit the application.
private static readonly AutoResetEvent waitHandle = new AutoResetEvent(false);
static void Main(string[] args)
{
var service = new Service();
// Fire and forget
Task.Run(() =>
{
service.Start();
var random = new Random(10);
while (true)
{
// Write here whatever your side car applications needs to do.
// In this sample we are just writing a random number to the Console (stdout)
Console.WriteLine($"Loop = {random.Next()}");
// Sleep as long as you need.
Thread.Sleep(1000);
}
});
// Handle Control+C or Control+Break
Console.CancelKeyPress += (o, e) =>
{
service.Stop();
// Allow the manin thread to continue and exit...
waitHandle.Set();
};
// Wait
waitHandle.WaitOne();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment