
正文
WPF 精修篇 长时间线程加取消功能
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
原文:WPF 精修篇 长时间线程加取消功能

<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; } }






