[英]Cancellation token and thread not working
我想取消一個線程,然后立即運行另一個線程。 這是我的代碼:
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();
}
}
使用CancellationTokens稱為“合作取消”,因為代碼必須與取消動作合作。 您僅在函數啟動時檢查一次,如果取消在該檢查之后發生,則取消永遠不會發生。
基於函數的名稱,我假設其中存在某種循環。 您的函數需要看起來像這樣。
private void WaveFormLoop(CancellationToken cancelToken)
{
try
{
while(someCondition) //Replace this with your real loop structure, I had to guess
{
cancelToken.ThrowIfCancellationRequested();
//some stuff to draw a waveform
}
}
catch (OperationCanceledException)
{
//Draw intitial Waveform
ResetWaveForm();
}
}
現在,它檢查循環的每次迭代是否都發生取消。 如果循環主體需要很長時間才能處理,則您可能希望在循環內部進行多個調用。
private void WaveFormLoop(CancellationToken cancelToken)
{
try
{
while(someCondition) //Replace this with your real loop structure, I had to guess
{
cancelToken.ThrowIfCancellationRequested();
Thread.Sleep(1000); //Fake doing work
cancelToken.ThrowIfCancellationRequested();
Thread.Sleep(1000); //Fake doing more work
}
}
catch (OperationCanceledException)
{
//Draw intitial Waveform
ResetWaveForm();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.