首页 > 其他分享 >CancellationTokenSource Cancel IsCancellationRequested

CancellationTokenSource Cancel IsCancellationRequested

时间:2024-04-06 21:45:05浏览次数:18  
标签:IsCancellationRequested cts Windows System CancellationTokenSource int Cancel us

//xaml
<Window x:Class="WpfApp37.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp37" WindowState="Maximized"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid TextBlock.FontSize="16">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="6">
            <TextBlock Text="From:"/>
            <TextBox Margin="10,2,2,2" Width="120" MaxLength="10" x:Name="_from"/>
            <TextBlock Text="To:" Margin="20,0,0,0"/>
            <TextBox Margin="10,2,2,2" Width="120" MaxLength="10" x:Name="_to"/>
        </StackPanel>
        <StackPanel Grid.Row="1" Orientation="Horizontal" Margin="6">
            <Button Content="Calculate" x:Name="calcBtn" Padding="4" Click="calc_Click" />
            <Button Content="Cancel" Padding="4" Margin="10,0,0,0" IsEnabled="False"
                    x:Name="_cancelBtn" Click="_cancelBtn_Click" />
        </StackPanel>
        <TextBlock Grid.Row="3" x:Name="_result" FontSize="20" Margin="6" HorizontalAlignment="Center"/>
         
    </Grid>
</Window>


//cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp37
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    { 
        CancellationTokenSource _cts; 

        public MainWindow()
        {
            InitializeComponent(); 
        }
         
        static int CountPrimes(int from, int to,CancellationToken ct)
        { 
            int total = 0;
            for (int i = from; i <= to; i++)
            {
                if (ct.IsCancellationRequested)
                {
                    return total;
                }
                bool isPrime = true;
                int limit = (int)Math.Sqrt(i);
                for (int j = 2; j <= limit; j++)
                {
                    if (i % j == 0)
                    {
                        isPrime = false;
                        break;
                    } 
                }
                if (isPrime)
                {
                    total++;
                }
            }
            return total;
        }

        private void calc_Click(object sender, RoutedEventArgs e)
        { 
            _result.Text = "Calculating...";
            int first=int.Parse(_from.Text),last=int.Parse(_to.Text);
            calcBtn.IsEnabled = false;
            _cancelBtn.IsEnabled = true;
            _cts=new CancellationTokenSource();
            ThreadPool.QueueUserWorkItem(x =>
            {
                int total = CountPrimes(first, last, _cts.Token);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _result.Text = _cts.IsCancellationRequested ? $"Cancelled to :{total}" :
                    $"Finished Total Primes :{total}"; 
                    _cancelBtn.IsEnabled = false;
                    calcBtn.IsEnabled = true;
                }));
            }); 
        }

        private void _cancelBtn_Click(object sender, RoutedEventArgs e)
        {
            if (_cts != null)
            {
                _cts.Cancel(); 
            }
        }
    }
}

 

 

 

 

 

标签:IsCancellationRequested,cts,Windows,System,CancellationTokenSource,int,Cancel,us
From: https://www.cnblogs.com/Fred1987/p/18117974

相关文章

  • 解决: java.util.concurrent.CancellationException详解
    解决:java.util.concurrent.CancellationException详解......
  • 在C#中使用 CancellationToken 处理异步任务
    来源:在C#中使用CancellationToken处理异步任务-知乎(zhihu.com)在.NETCore中使用异步编程已经很普遍了,你在项目中随处可见async和await,它简化了异步操作,允许开发人员,使用同步的方式编写异步代码,你会发现在大部分的异步方法中,都提供了CancellationToken参数,本文主要介......
  • 通过billing document V2 OData API cancel billing document 和通过 soap api 创建bi
    1:apihub找到相应的api,https://api.sap.com/package/SAPS4HANACloud/odata  通过执行cancelbillingdocument,可以发现cancelaction的payload和url 2:postaction在apihub中不能执行,需要到postman或者gatewayclient执行。 ......
  • 高并发下 MySQL Statement Cancellation Timer 的线程数暴涨
    微信公众号:运维开发故事作者:老郑问题描述线上业务高峰期CPU飙升,抓取threaddump发现 MySQLStatementCancellationTimer 的线程数比较多,接收到线上预警,分析一下原因。业务高峰:下面是一些可能相关的信息( mysql驱动,db连接池,orm框架)依赖信息:mysql-jdbc8.0.24druid1.2.8m......
  • Android应用开发长按拖拽-Flutter的LongPressDraggable控件回调函数onDraggableCancel
    onDraggableCanceled介绍LongPressDraggable的onDraggableCanceled回调在拖动被取消时触发。拖动可能会被取消,例如用户在拖动开始后移动了太快或在放置之前取消了拖动。onDraggableCanceled的使用以下是如何使用onDraggableCanceled的示例:LongPressDraggable<int>(//......
  • WepApi TaskCanceledException A任务已取消--async+await的方案替代task.Wait()可有效
     在.netCore中httpClient添加配置超时时长也没用services.AddHttpClient("PPHttpClient",config=>{config.DefaultRequestHeaders.Add("Accept","*/*");config.DefaultRequestHeaders.Add("A......
  • C#中CancellationToken和CancellationTokenSource用法
    C#中CancellationToken和CancellationTokenSource用法 之前做开发时,一直没注意这个东西,做了.netcore之后,发现CancellationToken用的越来越平凡了。这也难怪,原来.netframework使用异步的不是很多,而.netcore首推异步编程,到处可以看到Task的影子,而CancellationToken......
  • [GraphicBufferSource](id:5cd400000003,api:1,p:1674,c:23764) cancelBuffer: Buffer
    开发中遇到的问题,这个问题吧属于我们公司开发使用的RSR然后我们做好的app就是一个录屏软件将视频推到RSR当中去,可是推送的同时只会在RSR中出现一下我查看日志文件输出的信息唯一出现爆红的地方就是GraphicBufferSourcecancelBuffer:BufferQueuehasbeenabandoned这个,有没有经......
  • .NET Core的CancellationToken集成使用
    它用于在执行长时间运行的操作时,通过发送取消请求来终止操作。CancellationToken可以与异步操作一起使用,以便在操作执行期间检查是否已请求取消。它提供了一种优雅的方式来处理取消操作,避免了长时间运行的操作无法中断的问题。varhttpContext=Cfg.HttpContext......
  • TCC(Try/Confirm/Cancel)
    学习分布式事务心得:TCC(Try/Confirm/Cancel)在学习分布式事务的过程中,我深入研究了一种常见的分布式事务解决方案——TCC(Try/Confirm/Cancel)。TCC概述TCC是一种基于补偿机制的分布式事务处理模式。它将一个复杂操作拆分为三个阶段:尝试(Try)、确认(Confirm)和取消(Cancel),以确保多个服务......