[英]Use Parallel.ForEach without lists
I want to use Parallel.ForEach
as a multi-threading method that executes a code without lists or file reading.我想使用
Parallel.ForEach
作为多线程方法,在没有列表或文件读取的情况下执行代码。
I want to do it like this:我想这样做:
Parallel.ForEach
{
Console.WriteLine("test");
}
So it will write test
without stopping.所以它会不停地写
test
。 I will use an IF
statement to check if it should be stopped or no.我将使用
IF
语句来检查它是否应该停止。
Is it possible to use Parallel.ForEach
like that?可以像这样使用
Parallel.ForEach
吗?
Any help would be appreciated.任何帮助,将不胜感激。
Thanks!谢谢!
Multi-threading this is not going to achieve anything, but if you insist:多线程这不会实现任何目标,但如果您坚持:
bool _shouldStop { get; set; } = false;
bool _shouldStopSecondThread { get; set; } = false;
public static Main(string[] args)
{
Thread thread = new Thread(print);
Thread anotherThread = new Thread(anotherPrint);
thread.Start();
anotherThread.Start();
//your code here while the worker writes "Test" to console
if(condition) {
_shouldStop=true;
_shouldStopSecondThread=false;
}
}
//...
public void print()
{
while (!_shouldStop)
{
Console.WriteLine("test");
}
Console.WriteLine("worker terminated");
}
public void anotherPrint()
{
while (!_shouldStopSecondThread)
{
Console.WriteLine("test");
}
Console.WriteLine("worker terminated");
}
What you want is not very clear but you may try this approach:您想要的不是很清楚,但您可以尝试这种方法:
var parallelDrege = Environment.ProcessorCount;
while (true)
{
Parallel.For(0, parallelDrege, t =>
{
Console.WriteLine("test");
});
}
Set parallelDegre to the desired value and be aware that every batch will be processed in parallel but from batch to batch is a sequetial process.将 parallelDegre 设置为所需的值,并注意每个批次都将并行处理,但批次之间是一个连续的过程。
Hope this help!希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.