Last active
May 30, 2019 08:39
-
-
Save GFoley83/87521bc936dced925eb75c47bd27248e to your computer and use it in GitHub Desktop.
Gracefully handle exiting an async ASP.NET console app with CancellationTokenSource support
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 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 | |
} | |
} | |
} | |
} |
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 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