本文介绍了停止我的任务和我所有的等待任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个应用程序,它从我的 Listbox
中取出所有添加的文件并播放这些文件:
i have an application who take all the added files from my Listbox
and play this files:
IEnumerable<string> source
public void play()
{
Task.Factory.StartNew(() =>
{
Parallel.ForEach(source,
new ParallelOptions
{
MaxDegreeOfParallelism = 1 //limit number of parallel threads
},
file =>
{
//each file process via another class
});
}).ContinueWith(
t =>
{
OnFinishPlayEvent();
}
, TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
);
}
我的处理文件可以通过我的类属性停止,但如果我想停止所有文件等着我怎么办?
my processing file can be stop via my class property but if i want to stop all the filesthat waiting how can i do it ?
推荐答案
您需要设计您的例程以接受 CancellationToken
,然后触发一个 CancellationTokenSource.Cancel()
.
You need to design your routines to accept a CancellationToken
, and then trigger a CancellationTokenSource.Cancel()
.
这将允许您提供一种机制来合作取消您的工作.
This will allow you to provide a mechanism to cooperatively cancel your work.
有关详细信息,请参阅托管线程中的取消和MSDN 上的任务取消.
For details, see Cancellation in Managed Threads and Task Cancellation on MSDN.
这篇关于停止我的任务和我所有的等待任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!