线程取消主要使用的是 CancellationTokenSource 对象下的CancellationToken 取消标记,
代码如下
using Microsoft.EntityFrameworkCore; using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace EFCOREDB { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); #region 线程取消 TestThreancancel(); #endregion Console.Read(); } #region 线程取消 /// <summary> /// 线程取消 /// </summary> public static void TestThreancancel() { using CancellationTokenSource source = new CancellationTokenSource(); ThreadPool.QueueUserWorkItem(_ => TestThreancancel1(source.Token)); Thread.Sleep(TimeSpan.FromSeconds(3)); source.Cancel(); using CancellationTokenSource source1 = new CancellationTokenSource(); ThreadPool.QueueUserWorkItem((_) => { TestThreancancel2(source1.Token); }); //source1.CancelAfter(TimeSpan.FromSeconds(3)); Thread.Sleep(TimeSpan.FromSeconds(3)); source1.Cancel(); using CancellationTokenSource source2 = new CancellationTokenSource(); ThreadPool.QueueUserWorkItem((_) => { TestThreancancel3(source2.Token); }); //source2.CancelAfter(TimeSpan.FromSeconds(3)); Thread.Sleep(TimeSpan.FromSeconds(3)); source2.Cancel(); } /// <summary> /// 线程取消 /// </summary> public static void TestThreancancel1(CancellationToken token) { Console.WriteLine($"第一个线程开始执行"); for (int i = 0; i < 10; i++) { if (token.IsCancellationRequested) { Console.WriteLine($"第一个线程已经取消了。。。"); return; } Console.WriteLine($"第一个线程TestThreancancel 输出值:{i}"); Thread.Sleep(TimeSpan.FromSeconds(1)); //Console.WriteLine($"第一个线程TestThreancancel 输出值:{i}"); } Console.WriteLine($"第一个线程成功执行"); } /// <summary> /// 线程取消 /// </summary> public static void TestThreancancel2(CancellationToken token) { Console.WriteLine($"第二个线程开始执行"); bool isCanceled = false; token.Register(() => { isCanceled = true; }); for (int i = 0; i < 10; i++) { if (isCanceled) { Console.WriteLine($"第二个线程已经取消了。。。"); return; } Console.WriteLine($"第二个线程TestThreancancel 输出值:{i}"); Thread.Sleep(TimeSpan.FromSeconds(1)); //Console.WriteLine($"第二个线程TestThreancancel 输出值:{i}"); } Console.WriteLine($"第二个线程成功执行"); } /// <summary> /// 线程取消 /// </summary> public static void TestThreancancel3(CancellationToken token) { Console.WriteLine($"第三个线程开始执行"); try { for (int i = 0; i < 10; i++) { Console.WriteLine($"第三个线程TestThreancancel 输出值:{i}"); token.ThrowIfCancellationRequested(); Thread.Sleep(TimeSpan.FromSeconds(1)); //Console.WriteLine($"第三个线程TestThreancancel 输出值:{i}"); } Console.WriteLine($"第三个线程成功执行"); } catch (OperationCanceledException) { Console.WriteLine($"第三个线程已经取消了。。。"); } } #endregion } }