首页 > 编程语言 >浅谈C#中取消令牌CancellationTokenSource

浅谈C#中取消令牌CancellationTokenSource

时间:2024-05-22 22:52:52浏览次数:19  
标签:cancellationTokenSource Console 浅谈 C# CancellationTokenSource 取消 Token WriteLine

  • 基础操作 复制代码
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                cancellationTokenSource.Token.Register(() =>
                {
                    Console.WriteLine("取消了1111");
                });
                cancellationTokenSource.Token.Register(() =>
                {
                    Console.WriteLine("取消了2222");
                });
                cancellationTokenSource.Cancel();
    复制代码
    取消了2222
    取消了1111
  • 超时自动取消
  1. new CancellationTokenSource(3000);
  2. cancellationTokenSource.CancelAfter(3000);
  • 关联取消 复制代码
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                CancellationTokenSource cancellationTokenSource2 = new CancellationTokenSource();
                cancellationTokenSource.Token.Register(() =>
                {
                    Console.WriteLine("取消了1111");
                });
                cancellationTokenSource2.Token.Register(() =>
                {
                    Console.WriteLine("取消了2222");
                });
                var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token,
                    cancellationTokenSource2.Token);
                linkedTokenSource.Token.Register(() =>
                {
                    Console.WriteLine("关联令牌被取消了");
                });
                //cancellationTokenSource.Cancel();
                cancellationTokenSource2.Cancel();
    复制代码
    关联令牌被取消了
    取消了2222
    令牌1和2的任意一个取消,关联令牌linkedTokenSource就会被取消。但是关联令牌linkedTokenSource取消,令牌1和2并不会取消。
  • 判断取消 复制代码
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                cancellationTokenSource.Token.Register(() =>
                {
                    Console.WriteLine("取消了1111");
                });
                Task.Run(async () =>
                {
                    while (!cancellationTokenSource.IsCancellationRequested)
                    {
                        Console.WriteLine("一直在执行...");
                        await Task.Delay(1000);
                    }
                });
                cancellationTokenSource.CancelAfter(3000);
    复制代码
    一直在执行...
    一直在执行...
    一直在执行...
    取消了1111
    复制代码
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                Task.Run(async () =>
                {
                    try
                    {
                        while (true)
                        {
                            //如果操作被取消则直接抛出异常
                            cancellationTokenSource.Token.ThrowIfCancellationRequested();
                            Console.WriteLine("一直在执行...");
                            await Task.Delay(1000);
                        }
                    }
                    catch (OperationCanceledException ex)
                    {
                        Console.WriteLine("取消了!");
                    }
                });
                cancellationTokenSource.CancelAfter(3000);
    复制代码
    一直在执行...
    一直在执行...
    一直在执行...
    取消了!

    使用ThrowIfCancellationRequested会抛出OperationCanceledException异常,需要自己捕获处理

标签:cancellationTokenSource,Console,浅谈,C#,CancellationTokenSource,取消,Token,WriteLine
From: https://www.cnblogs.com/webenh/p/18207304

相关文章

  • CodeForces 1965F Conference
    洛谷传送门CF传送门考虑题目可以看成天和人的匹配,因此判断单个日期区间\([l,r]\)可以考虑Hall定理,设\(N(S)\)为在\(S\)这些天有空的人的数量,定义\(S\)合法当且仅当\(|N(S)|\ge|S|\),那么\([l,r]\)合法当且仅当\(\forallS\subseteq[l,r]\),\(S\)合法。猜......
  • 96-Unique Binary Search Trees 二叉搜索树的数量
    问题描述链接:https://leetcode.com/problems/unique-binary-search-trees/description/Givenaninteger n,return thenumberofstructurallyunique BST's(binarysearchtrees)whichhasexactly n nodesofuniquevaluesfrom 1 to n.解释:给定一个整数n,求1~n......
  • websocket和http的区别
    1、websocket1.1介绍WebSocket是一种实时通信协议,它允许客户端和服务器之间进行双向通信,而不需要每次请求都重新建立连接。WebSocket是HTML5中的新功能,它建立在HTTP协议之上,通过握手协议来建立持久化的连接。WebSocket的握手协议比HTTP的握手协议更简单,因为WebSocket......
  • 解决老旧电脑在win7中浏览器访问https网站出现的Let‘sEncrypt证书过期的问题
        原因LetsEncrypt证书未过期,但是其顶级ca根证书“DSTRootCAX3”在2021-09-01过期了,老旧设备上的win系统会被影响到。解决步骤下载三张Letsencrypt的根证书“DSTRootCAX3”的最新版本,包含isrgrootx1.der+isrg-root-x2.der+lets-encrypt-r3.der:https://do......
  • Spring Boot —— Spring Security
    引入依赖Springboot版本2.7.6<properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.repo......
  • C++高性能服务器框架—协程模块
    协程模块概述一、概念可以简单的认为:协程就是用户态的线程,但是上下文切换的时机是靠调用方(写代码的开发人员)自身去控制的;对比首先介绍一下为什么要使用协程。从了解进程,线程,协程之间的区别开始。从定义来看进程是资源分配和拥有的基本单位。进程通过内存映射拥有独立的代......
  • 记录一个按列内容拆分Excel文件的小方法
    importtkinterastkimportosimporttkinter.filedialogimporttkinter.simpledialogimportpandasaspdimporttkinter.messageboximporttkinter.ttkimporttracebackglobalcolumn,sheet_origlobalcombox_2#按内容分类defsplit_by_group():#获取需......
  • 记录一个按文档长度分割Excel文件的方法
    importtkinterastkimportpandasaspdimporttkinter.filedialogimportosimporttracebackwindows=tk.Tk()####按长度拆分——自定义函数##拆分函数defdivision_by_length(iterable,length):iterable_len=len(iterable)start=0while1:......
  • C++实现128位整数类
    如何编写一个128位的整数现在的大部分的计算机编程语言都包含了64位的有符号整数和无符号整数,有的甚至还提供了128位的整数和大数,比如:\(C\#\):System.Int128,System.UInt128\(Rust\):i128,u128但是在C/C++中并未发现uint128_t/int128_t,尽管在某些平台下可以看到__int1......
  • [20] C++虚幻引擎热更新
    Day1大纲行为树节点网络PDF网络系统内容Task节点FinishWithResult:MoveDirectlyToWard:PushPawnAction:运行至当前队列节点首节点 RunBehaviorDynamic:动态运行子行为树SetTagCooldown:WaitBlackboardTime:装饰器节点GamePlayTagCondition......