27 线程执行上下文和取消
27.3 执行上下文
CallContext.LogicalSetData("Name", "Jeffrey"); ThreadPool.QueueUserWorkItem(obj => { Console.WriteLine($"Name={CallContext.LogicalGetData("Name")}"); }); ExecutionContext.SuppressFlow(); ThreadPool.QueueUserWorkItem(obj => { Console.WriteLine($"Name={CallContext.LogicalGetData("Name")}"); }); ExecutionContext.RestoreFlow();
27.4 协作式取消和超时
static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); ThreadPool.QueueUserWorkItem(o => Count(cts.Token, 1000)); Console.WriteLine("press enter to cancel the operation"); Console.ReadLine(); cts.Cancel(); Console.ReadKey(); } private static void Count(CancellationToken token, int countTo) { for (int count = 0; count < countTo; count++) { if (token.IsCancellationRequested) { Console.WriteLine("Count is cancel"); break; } Console.WriteLine(count); Thread.Sleep(200); } Console.WriteLine("Count is done"); }
CancellationTokenSource cts = new CancellationTokenSource(); cts.Token.Register(() => { Console.WriteLine("Canceled 1"); }); cts.Token.Register(() => { Console.WriteLine("Canceled 2"); }); cts.Cancel(); CancellationTokenSource cts1 = new CancellationTokenSource(); cts1.Token.Register(() => { Console.WriteLine("Cts1 canceled"); }); CancellationTokenSource cts2 = new CancellationTokenSource(); cts2.Token.Register(() => { Console.WriteLine("Cts2 canceled"); }); var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts1.Token, cts2.Token); linkedCts.Token.Register(() => { Console.WriteLine("linked cancel"); }); cts2.Cancel(); Console.WriteLine("cts1={0} cts2={1} linked={2}", cts1.IsCancellationRequested, cts2.IsCancellationRequested, linkedCts.IsCancellationRequested); /* Canceled 2 Canceled 1 linked cancel Cts2 canceled cts1=False cts2=True linked=True */