我有一个应用程序从 Listbox 中获取所有添加的文件并播放此文件。
这是IEnumerable<string> source
通过另一个类获取和播放文件的类:
public CancellationTokenSource _tokenSource { get; set; }
private IEnumerable<string> _source;
public void play(PacketDevice selectedOutputDevice, double speed, int parallelThreads)
{
var token = _tokenSource.Token;
if (token.IsCancellationRequested)
{
return;
}
Task.Factory.StartNew(() =>
{
try
{
Parallel.ForEach(_source,
new ParallelOptions
{
MaxDegreeOfParallelism = 1;
},
file =>
{
processFile(file, selectedOutputDevice, speed, parallelThreads);
//token.ThrowIfCancellationRequested();
});
}
catch (AggregateException)
{
}
}, _tokenSource.Token).ContinueWith(
t =>
{
OnFinishPlayEvent();
}
, TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
);
}
从停止按钮单击事件下的主窗体中,我正在更改_tokenSource.Cancel();
,但我的问题是我的循环继续工作并且没有停止。