[英]Use Parallel.ForEach without lists
我想使用Parallel.ForEach
作为多线程方法,在没有列表或文件读取的情况下执行代码。
我想这样做:
Parallel.ForEach
{
Console.WriteLine("test");
}
所以它会不停地写test
。 我将使用IF
语句来检查它是否应该停止。
可以像这样使用Parallel.ForEach
吗?
任何帮助,将不胜感激。
谢谢!
多线程这不会实现任何目标,但如果您坚持:
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");
}
您想要的不是很清楚,但您可以尝试这种方法:
var parallelDrege = Environment.ProcessorCount;
while (true)
{
Parallel.For(0, parallelDrege, t =>
{
Console.WriteLine("test");
});
}
将 parallelDegre 设置为所需的值,并注意每个批次都将并行处理,但批次之间是一个连续的过程。
希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.