1.写页面,2行2列,写4个button给每个都写一个click
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Grid.Row="0" Grid.Column="0" Content="开始" Click="Button_Click"/>
<Button Grid.Row="0" Grid.Column="1" Content="取消" Click="Button_Click_1"/>
<Button Grid.Row="1" Grid.Column="0" Content="暂停" Click="Button_Click_2"/>
<Button Grid.Row="1" Grid.Column="1" Content="继续" Click="Button_Click_3"/>
</Grid>
2.写业务(具体自己看)
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
//取消任务源信号
private CancellationTokenSource cancellationTokenSource=new CancellationTokenSource();
//手动停止事件
private ManualResetEvent ManualResetEvent = new ManualResetEvent(true);
//启动
private void Button_Click(object sender, RoutedEventArgs e)
{
if (cancellationTokenSource.IsCancellationRequested)
{
cancellationTokenSource = new CancellationTokenSource();
}
Task.Run(() =>
{
int count = 0;
while (!cancellationTokenSource.IsCancellationRequested)
{
//用来控制是否需要暂停和继续
ManualResetEvent.WaitOne();
//实际开发中要写的业务
count++;
Thread.Sleep(300);
Console.WriteLine(count);
}
},cancellationTokenSource.Token);
}
//取消
private void Button_Click_1(object sender, RoutedEventArgs e)
{
cancellationTokenSource.Cancel();
}
//暂停
private void Button_Click_2(object sender, RoutedEventArgs e)
{
ManualResetEvent.Reset();
}
//继续
private void Button_Click_3(object sender, RoutedEventArgs e)
{
ManualResetEvent.Set();
}
}