public class Example { public static void Main() { CancellationTokenSource cts = new CancellationTokenSource(); var thread = new Thread(ThreadWork); thread.Start(cts.Token); while (true) { if(Console.ReadKey().KeyChar == 'c') { Console.WriteLine("请求取消线程的执行"); cts.Cancel(); break; } } Console.ReadLine(); }
public static void Main() { var autoResetEvent = new AutoResetEvent(false); var cts = new CancellationTokenSource(); var state = new { ValueAvailableEvent = autoResetEvent, CancellationToken = cts.Token }; var threadConsumer = new Thread(ConsumerThreadWork); var threadProducter = new Thread(ProducterThreadWork);
while (true) { if (Console.ReadKey().KeyChar == 'c') { Console.WriteLine("请求取消线程的执行"); cts.Cancel(); break; } } Console.ReadLine();
} public static void ProducterThreadWork(dynamic state) { var valueAvailableEvent = (AutoResetEvent)state.ValueAvailableEvent; var cancellationToken = (CancellationToken)state.CancellationToken; var rand = new Random(); while (!cancellationToken.IsCancellationRequested) { Value = rand.Next(); Console.WriteLine("/r/n产生一个值{0}", Value); valueAvailableEvent.Set(); Thread.Sleep(500); }
Console.WriteLine("生产者线程被取消。"); }
public static void ConsumerThreadWork(dynamic state) { var valueAvailableEvent = (AutoResetEvent)state.ValueAvailableEvent; var cancellationToken = (CancellationToken)state.CancellationToken; var events = new[] { valueAvailableEvent, cancellationToken.WaitHandle };
while (true) { var eventIndex = WaitHandle.WaitAny(events); // 处理数据 if (eventIndex == 0) { Console.WriteLine("处理值{0}。", Value); } // 处理取消事件 else if (eventIndex == 1) { Console.WriteLine("消费者线程被取消。"); break; } } } }