Created
February 6, 2019 22:40
-
-
Save jennings/381ff072c3b35cc0f2af2a96fff9d373 to your computer and use it in GitHub Desktop.
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; | |
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