线程取消
线程取消主要使用的是 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 线程取消 /// /// 线程取消 /// 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(); } /// /// 线程取消 /// 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($"第一个线程成功执行"); } /// /// 线程取消 /// 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($"第二个线程成功执行"); } /// /// 线程取消 /// 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 }}
龙腾一族至尊龙骑
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~