namespace WpfApplication1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
// create the cancellation token source
private CancellationTokenSource TokenSource = new CancellationTokenSource();
private Task CurrentTask;
public MainWindow()
{
InitializeComponent();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
// create the cancellation token
CancellationToken token = TokenSource.Token;
// create the task
CurrentTask = new Task(() =>
{
for (int i = 0; i < int.MaxValue; i++)
{
if (token.IsCancellationRequested)
{
Debug.WriteLine("Task cancel detected");
break;
//throw new OperationCanceledException(token);
}
else
{
Debug.WriteLine("Int value {0}", i);
}
}
}, token);
// start the task
CurrentTask.Start();
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
if (CurrentTask != null)
{
if (CurrentTask.Status == TaskStatus.Running) { }
{
TokenSource.Cancel();
Debug.WriteLine("Task cancel");
}
}
}
}
}