Skip to content

Instantly share code, notes, and snippets.

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 GFoley83/87521bc936dced925eb75c47bd27248e to your computer and use it in GitHub Desktop.
Save GFoley83/87521bc936dced925eb75c47bd27248e to your computer and use it in GitHub Desktop.
Gracefully handle exiting an async ASP.NET console app with CancellationTokenSource support
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
// Cancellation Tokens - https://docs.microsoft.com/en-us/previous-versions/dd997289(v=vs.110)
private static readonly CancellationTokenSource canToken = new CancellationTokenSource();
static void Main(string[] args)
{
Console.WriteLine("Application has started. Ctrl-C to end");
Console.CancelKeyPress += (sender, eventArgs) =>
{
Console.WriteLine("Cancel event triggered");
canToken.Cancel();
eventArgs.Cancel = true;
};
MainAsync(args).GetAwaiter().GetResult();
Console.WriteLine("Now shutting down");
Thread.Sleep(1000);
}
static async Task MainAsync(string[] args)
{
await Worker();
}
async static Task Worker()
{
while (!canToken.IsCancellationRequested)
{
// do work
Console.WriteLine("Worker is working");
await Task.Delay(1000); // arbitrary delay
}
}
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
// Cancellation Tokens - https://docs.microsoft.com/en-us/previous-versions/dd997289(v=vs.110)
private static readonly CancellationTokenSource canToken = new CancellationTokenSource();
static async Task Main(string[] args)
{
Console.WriteLine("Application has started. Ctrl-C to end");
Console.CancelKeyPress += (sender, eventArgs) =>
{
Console.WriteLine("Cancel event triggered");
canToken.Cancel();
eventArgs.Cancel = true;
};
await Worker();
Console.WriteLine("Now shutting down");
await Task.Delay(1000);
}
async static Task Worker()
{
while (!canToken.IsCancellationRequested)
{
// do work
Console.WriteLine("Worker is working");
await Task.Delay(1000); // arbitrary delay
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment