例子:
CancellationTokenSource cts ;
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Task.Run(() => {
try
{
Thread.Sleep(50000);//鸡肋的地方是如果这个地方需要很就才执行玩的话。。。
if (cts.Token.IsCancellationRequested)
{
throw new OperationCanceledException();
}
}
catch(OperationCanceledException ex) {
MessageBox.Show("Cancled");
}
});
}
private void Button_Click(object sender, RoutedEventArgs e)
{
cts = new CancellationTokenSource();
cts.Cancel();
}
我感觉这个是个鸡肋,有点脱了裤子放屁的感觉。自己设置一个全局标准退出线程是一样的效果。主要是这个做不到立即退出正在执行的线程的效果。CancellationTokenSource.Cancel() 不能对工作线程产生影响,只是设置一个标志。。。。。。所以很鸡肋,不知道我理解得对不对。
有时候我们需要强制终止线程执行。这个CancellationTokenSource就无能为力了。
还需要如下传统方式来:
private Thread _myThread ;
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{ _myThread = new Thread(SomeThreadMethod);
_myThread.Start();
}
private void SomeThreadMethod()
{
// do whatever you want
try
{
while (true)
{
Thread.Sleep(1000000);
Debug.Print(""+DateTime.Now );
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
private void KillTheThread()
{
_myThread.Abort();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
KillTheThread();
}