我尝试了解如何创建取消任务的按钮。 这是我的代码,但它没有取消任务:
public partial class MainWindow : Window
{
CancellationTokenSource CTS;
CancellationToken CT;
public MainWindow()
{
InitializeComponent();
CTS = new CancellationTokenSource();
CT = CTS.Token;
btnCancel.Click += btnCancelling;
btnDoWork.Click += btnDoingWork;
}
private void btnCancelling (object sender, RoutedEventArgs e)
{
CTS.Cancel();
}
private void btnDoingWork (object sender, RoutedEventArgs e)
{
try
{
DoWork (CT);
} catch (AggregateException ae)
{
foreach (var inner in ae.InnerExceptions)
{
if (inner is TaskCanceledException)
{
MessageBox.Show("The task was cancelled.");
}
else
{
throw;
}
}
}
}
private void DoWork (CancellationToken CT)
{
Task task = new Task(() =>
{
Thread.Sleep(5000);
MessageBox.Show("WorkIsDone");
CT.ThrowIfCancellationRequested();
}, CT);
task.Start();
}
}
DoWork()方法工作正常,它显示消息"工作完成"睡了5秒后
我已经在StackOverflow上阅读了非常勤奋的其他类似主题,但它们是关于从Main()方法调用Cancel(),但是如何创建一个特殊按钮来完成这项工作?
如何修改我的代码以在睡眠期间取消DoWork()方法?