如何从我的主线程中杀死 Parallel.ForEach 生成的所有线程?
场景如下:
我有一个正在运行的 Windows 服务。 OnStart()
它设置一个将调用函数的计时器(我们称之为 ProcessEvent()
)。 ProcessEvent
内的代码是关键部分,因此只有一个线程可以执行以下操作:
private void ProcessEvent(object sender, ElapsedEventArgs e)
{
lock(lockObj)
{
string[] list = GetList();
Parallel.ForEach(list, item => { ProcessItem(item) });
}
}
ProcessItem
可能需要很长时间。
现在,当服务停止时,我的 OnStop() 当前只是停止并处理计时器。但是我注意到,即使服务停止后,仍有线程仍在运行ProcessItem()
。
那么,我如何杀死该程序生成的所有正在运行的线程(主要是由 Parallel.ForEach 生成的线程,以及任何正在等待 ProcessEvent 中的锁的线程)?
我知道如果我自己创建线程,我可以将 isBackground 设置为 true,当进程终止时它都会被杀死,但我不会手动创建这些线程。
Here's the scenario:
I have a Windows Service that's running. OnStart()
it sets up a timer that will call a function (let's call it ProcessEvent()
). The code inside ProcessEvent
is a critical section, so only one thread can do the following:
private void ProcessEvent(object sender, ElapsedEventArgs e)
{
lock(lockObj)
{
string[] list = GetList();
Parallel.ForEach(list, item => { ProcessItem(item) });
}
}
ProcessItem
can potentially take a long time.
Now when the service is stopped my OnStop()
currently just stops and disposes the timer. However I noticed that even after service is stopped there are threads that are still running ProcessItem()
.
So how can I kill all running threads spawned by this program (mainly the ones spawned by the Parallel.ForEach
but also any that are waiting on the lock in ProcessEvent
)?
I know that had I created the thread myself I could set isBackground
to true and it will all get killed when process dies but I don't create these threads manually.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 Parallel.ForEach 接受带有 ParallelLoopState 参数。检查主体中的标志以查看执行是否应该继续,否则终止它:
Look into the overloads of Parallel.ForEach that take a delegate with a ParallelLoopState parameter. Check a flag in the body to see if execution should continue, otherwise kill it:
使用 CancellationToken 结构。阅读此和此了解更多信息。
Use the CancellationToken structure. Read this and this for more information.