Created
March 8, 2019 21:41
-
-
Save AlbertoDePena/a460af58011dfe8e5dba1e5706095f94 to your computer and use it in GitHub Desktop.
Gracefully exit dotnet console app in docker container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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