Skip to content

Instantly share code, notes, and snippets.

@runesoerensen
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save runesoerensen/bc2575d5c08610308ffb to your computer and use it in GitHub Desktop.
Save runesoerensen/bc2575d5c08610308ffb to your computer and use it in GitHub Desktop.
Simple console application that supports graceful shutdown
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