[英]How to Terminate Threads that started within foreach loop in C#
I started multiple threads by for each loop in my windows service.I didn't mention any name for these threads.How can i terminate these thread. 我在Windows服务中为每个循环启动了多个线程。我没有提到这些线程的任何名称。如何终止这些线程。 I use the following code to create threads.
我使用以下代码创建线程。
new Thread(() =>
{
foreach (MyClass detail in MyclassList)
{
DoWork(detail);
}
}).Start();
By starting these threads i create a schedule task for each details.Can i dispose this thread after Scheduling is done and How? 通过启动这些线程,我为每个详细信息创建一个计划任务。完成计划后,我可以处置该线程吗?
Forcibly terminating threads is never a good idea. 强制终止线程绝不是一个好主意。 What you should really be doing is putting some suitably designed "should I continue" check inside the loop, that you can set to "no" externally.
您真正应该做的是在循环中放入一些经过适当设计的“我应该继续”检查,以便您可以在外部设置为“ no”。 How to do that depends a bit more on context... For example:
如何做到这一点更多取决于上下文...例如:
int shouldExit = 0;
new Thread(() =>
{
foreach (MyClass detail in MyclassList)
{
if(Thread.VolatileRead(ref shouldExit) != 0) break;
DoWork(detail);
}
}).Start();
...
// to terminate loop:
Thread.VolatileWrite(ref shouldExit, 1);
There are, however, a myriad of ways to sort out a thread-safe exit test; 但是,有多种方法可以对线程安全的退出测试进行分类。 the only slightly tricky thing is keeping hold of some kind of context with access to the thing being checked.
唯一有些棘手的事情是通过访问要检查的事物来保持某种上下文。
First, I would use the Task
class instead of directly creating a new thread. 首先,我将使用
Task
类而不是直接创建新线程。 Then, I would use the builtin TPL cancellation mechanisms. 然后,我将使用内置的TPL取消机制。 Here is what it would look like.
这就是它的样子。
var cts = new CancellationTokenSource();
var token = cts.Token;
var task = Task.Factory.StartNew(
() =>
{
foreach (MyClass detail in MyclassList)
{
ct.ThrowIfCancellationRequested();
DoWork(detail);
}
}, cts.Token);
// Do other stuff here.
cts.Cancel(); // Request cancellation.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.