停止我的任务和所有等待的任务
本文关键字:任务 等待 我的 | 更新日期: 2023-09-27 18:16:40
我有一个应用程序谁采取所有添加的文件从我的Listbox
和播放这个文件:
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
);
}
我的处理文件可以通过我的类属性停止,但如果我想停止所有的文件我该怎么做呢?
您需要设计您的例程来接受CancellationToken
,然后触发CancellationTokenSource.Cancel()
。
这将允许您提供一种机制来协同取消您的工作。
详情请参见托管线程取消和MSDN上的任务取消。
如果要停止并行循环,请使用ParallelLoopState
类的实例。要取消任务,您需要使用CancellationToken
。由于要在任务中嵌入并行循环,因此可以简单地向任务传递一个取消令牌。请记住,如果您选择等待您的任务,这将抛出您必须捕获的OperationCanceledException。
例如,为了便于讨论,我们假设在你的类中有其他东西将调用一个委托,该委托将设置取消令牌。
CancellationTokenSource _tokenSource = new CancellationTokenSource();
//Let's assume this is set as the delegate to some other event
//that requests cancellation of your task
void Cancel(object sender, EventArgs e)
{
_tokenSource.Cancel();
}
void DoSomething()
{
var task = Task.Factory.StartNew(() => {
// Your code here...
}, _tokenSource.Token);
try {
task.Wait();
}
catch (OperationCanceledException) {
//Carry on, logging that the task was canceled, if you like
}
catch (AggregateException ax) {
//Your task will throw an AggregateException if an unhandled exception is thrown
//from the worker. You will want to use this block to do whatever exception handling
//you do.
}
}
请记住,有更好的方法可以做到这一点(这里我是从记忆中输入的,所以可能会有一些语法错误之类的),但这应该让您开始。