Skip to content

Instantly share code, notes, and snippets.

@jennings
Created February 6, 2019 22:40
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 jennings/381ff072c3b35cc0f2af2a96fff9d373 to your computer and use it in GitHub Desktop.
Save jennings/381ff072c3b35cc0f2af2a96fff9d373 to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
var worker = new Thread(Worker);
using (var shutdown = new CancellationTokenSource())
{
worker.Start(shutdown.Token);
Log("PARENT", "Press a key to cancel the 'shutdown' token");
Console.ReadKey();
Log("PARENT", "Cancelling the 'shutdown' token");
shutdown.Cancel();
}
Log("PARENT", "Waiting for worker thread to finish");
worker.Join();
Log("PARENT", "Worker thread finished");
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
static void Worker(object param)
{
var cancellationTokenFromParent = (CancellationToken)param;
using (var timerCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenFromParent))
{
Log("WORKER", "Cancelling after 5 seconds");
timerCts.CancelAfter(TimeSpan.FromSeconds(5));
timerCts.Token.WaitHandle.WaitOne();
Log("WORKER", "Cancellation requested");
Log("WORKER", "Timer token: IsCancellationRequested = {0}", timerCts.Token.IsCancellationRequested);
Log("WORKER", "Shutdown token: IsCancellationRequested = {0}", cancellationTokenFromParent.IsCancellationRequested);
}
}
static void Log(string source, string message, params object[] args)
{
Console.WriteLine($"[{DateTime.Now.ToString("hh:mm:ss.fff")}] {source.ToUpper()}: {message}", args);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment