- <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;
- }
- }
原文地址:https://www.cnblogs.com/lonelyxmas/p/12075537.html
时间: 2024-10-13 16:34:44