我想取消一个线程并在之后运行另一个线程。这是我的代码:
private void ResetMedia(object sender, RoutedEventArgs e)
{
cancelWaveForm.Cancel(); // cancel the running thread
cancelWaveForm.Token.WaitHandle.WaitOne(); // wait the end of the cancellation
cancelWaveForm.Dispose();
//some work
cancelWaveForm = new CancellationTokenSource(); // creating a new cancellation token
new Thread(() => WaveFormLoop(cancelWaveForm.Token)).Start(); // starting a new thread
}
当我调用此方法时,第一个线程不会停止,第二个线程开始运行......
但如果我跳过最后两行它可以工作:
private void ResetMedia(object sender, RoutedEventArgs e)
{
cancelWaveForm.Cancel(); // cancel the running thread
cancelWaveForm.Token.WaitHandle.WaitOne(); // wait the end of the cancellation
cancelWaveForm.Dispose();
//some work
//cancelWaveForm = new CancellationTokenSource(); // creating a new cancellation token
//new Thread(() => WaveFormLoop(cancelWaveForm.Token)).Start(); // starting a new thread
}
为什么停不下来?
编辑 1:
private void WaveFormLoop(CancellationToken cancelToken)
{
try
{
cancelToken.ThrowIfCancellationRequested();
//some stuff to draw a waveform
}
catch (OperationCanceledException)
{
//Draw intitial Waveform
ResetWaveForm();
}
}