-
-
Save runesoerensen/bc2575d5c08610308ffb to your computer and use it in GitHub Desktop.
Simple console application that supports graceful shutdown
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.IO; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace GracefulShutdownApplication | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var processCancellationToken = new CancellationTokenSource(); | |
SetupShutdownWatcher(processCancellationToken); | |
var task = Task.Factory.StartNew(token => | |
{ | |
while (true) | |
{ | |
Console.WriteLine("Doing work"); | |
Thread.Sleep(1000); | |
if (processCancellationToken.IsCancellationRequested) | |
{ | |
Console.WriteLine("Task is being cancelled. Aborting job execution"); | |
break; | |
} | |
Console.WriteLine("Doing more work"); | |
Thread.Sleep(1000); | |
} | |
}, processCancellationToken); | |
try | |
{ | |
task.Wait(processCancellationToken.Token); | |
} | |
catch (OperationCanceledException) | |
{ | |
Console.WriteLine("Task was cancelled, cleaning up"); | |
Thread.Sleep(3000); | |
Console.WriteLine("Cleaned up"); | |
} | |
} | |
private static void SetupShutdownWatcher(CancellationTokenSource cancellationToken) | |
{ | |
var shutdownFilePath = Environment.GetEnvironmentVariable("WORKER_SHUTDOWN_FILE"); | |
var directoryPath = Path.GetDirectoryName(shutdownFilePath); | |
var fileSystemWatcher = new FileSystemWatcher(directoryPath); | |
FileSystemEventHandler changed = (o, e) => | |
{ | |
if (e.FullPath.IndexOf(Path.GetFileName(shutdownFilePath), StringComparison.OrdinalIgnoreCase) >= 0) | |
{ | |
Console.WriteLine("Shutdown file notification detected"); | |
cancellationToken.CancelAfter(1000); | |
} | |
}; | |
fileSystemWatcher.Created += changed; | |
fileSystemWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastWrite; | |
fileSystemWatcher.IncludeSubdirectories = false; | |
fileSystemWatcher.EnableRaisingEvents = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment