WPF 精修篇 长时间线程加取消功能
2024-08-30 07:13:07
-
<Grid>
-
<Grid.RowDefinitions>
-
<RowDefinition Height="11*"/>
-
<RowDefinition Height="29*"/>
-
</Grid.RowDefinitions>
-
<StackPanel Orientation="Horizontal" Margin="0" VerticalAlignment="Center">
-
<Label>开始数据</Label>
-
<TextBox x:Name="beginText" HorizontalAlignment="Left" Height="31" TextWrapping="Wrap" Text="100" VerticalAlignment="Top" Width="100"/>
-
<Label>结束数据</Label>
-
<TextBox x:Name="endText" HorizontalAlignment="Left" Height="31" TextWrapping="Wrap" Text="1000000000" VerticalAlignment="Top" Width="100"/>
-
<Button x:Name="button" Content="开始" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Click="Button_Click"/>
-
<Button x:Name="Cancel" Content="取消" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Click="Cancel_Click"/>
-
</StackPanel>
-
<StackPanel Margin="0" Grid.Row="1">
-
<TextBlock x:Name="odd" TextWrapping="Wrap" Text="奇数数量:"/>
-
<TextBlock x:Name="even" TextWrapping="Wrap" Text="偶数数量:"/>
-
</StackPanel>
-
</Grid>
-
private int oddcount =0;
-
private int evencount =0;
-
public void Make(int from ,int to)
-
{
-
for (int i = from; i < to; i++)
-
{
-
if (TokenSource.IsCancellationRequested)
-
{
-
evencount = -1;
-
oddcount = -1;
-
return;
-
}
-
if (i % 2 == 0)
-
{
-
evencount++;
-
}
-
else
-
{
-
oddcount++;
-
}
-
}
-
}
-
private void Button_Click(object sender, RoutedEventArgs e)
-
{
-
int from=0;
-
int to = 0;
-
if(int.TryParse(beginText.Text,out from)&&int.TryParse(endText.Text,out to) )
-
{
-
button.IsEnabled = false;
-
ThreadPool.QueueUserWorkItem(_ =>
-
{
-
TokenSource = new CancellationTokenSource();
-
Make(from, to);
-
-
Dispatcher.BeginInvoke(new Action(() =>
-
{
-
if (oddcount < 0 || evencount < 0)
-
{
-
odd.Text = "操作取消";
-
even.Text = "操作取消";
-
}
-
else
-
{
-
odd.Text = "奇数数量:" + oddcount;
-
even.Text = "偶数数量:" + evencount;
-
}
-
button.IsEnabled = true;
-
}));
-
-
});
-
-
}
-
-
}
-
-
public CancellationTokenSource TokenSource = null;
-
private void Cancel_Click(object sender, RoutedEventArgs e)
-
{
-
if (TokenSource != null)
-
{
-
TokenSource.Cancel();
-
TokenSource = null;
-
}
-
-
}
最新文章
- 关于SIGSEGV错误及处理方法(转)
- python enumerate函数用法
- iframe与主框架跨域相互访问方法【转】
- Project中分清楚挣值项
- oralce创建用户
- js变量作用域
- cas 单点登录配置
- tomcat 远程 调试 eclipse
- jsp中的动作标签
- iOS使用带字体图标的UIButton(支持各种方向)
- JAVA WEB之Spring4.x JdbcTemplate
- CentOS6.8下MySQL MHA架构搭建笔记
- elastic-job详解(三):Job的手动触发功能
- spring @Value注解#和$区别
- Zookeeper命令行auth,digest
- 读书笔记(05) - 事件 - JavaScript高级程序设计
- pgm6
- form数据请求参数格式
- ROM初始化HEX文件
- 遇到can not resolve app 依赖包的问题
热门文章
- MQTT实战1&#160;- 使用Apache Apollo代理服务器实现mqtt通信
- shuffle调优
- Lerp在X秒内插值
- XML 配置文件,知识点
- 整合SpringTask实现定时任务
- R-FCN:
- LG4819/BZOJ2438 「中山市选2011」杀人游戏 Tarjan缩点+概率
- 遍历hashmap 的四种方法
- phoenix hbase Can&#39;t get master address from ZooKeeper; znode data == null
- elasticsearch入门及安装