C# 使用不带列表的Parallel.ForEach
我想使用C# 使用不带列表的Parallel.ForEach,c#,multithreading,parallel.foreach,C#,Multithreading,Parallel.foreach,我想使用Parallel.ForEach作为一种多线程方法,在不读取列表或文件的情况下执行代码 我想这样做: Parallel.ForEach { Console.WriteLine("test"); } 因此,它将不停地编写test。我将使用IF语句检查它是否应该停止 有没有可能像那样使用Parallel.ForEach 任何帮助都将不胜感激 谢谢 多线程这不会有任何效果,但如果您坚持: bool _shouldStop { get; set; } = false; bool _
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设置为所需值,并注意每个批次将并行处理,但批次之间是一个顺序过程
希望这有帮助 为什么要使用
foreach
循环而不进行任何迭代?这里的主要目标是什么ForEach
似乎无关紧要。@SelmanGenç-我希望它执行一个正常的代码,而不是在列表上迭代。为什么要使用构造来迭代一个没有的列表?请解释一下如何使用普通的foreach
@NirmalSubedi来实现这一点-我希望它是多线程的。与其检查if
语句中的某些条件(如您在问题中提到的),不如将其用作循环的条件:while(someCondition==true){Console.WriteLine(“Test”)}
此外,我强烈建议您在旧的线程API上更新任务API。如何终止此操作?使用CPUsenEnvironment.ProcessorCount的数量或其中的一个因素:2*Environment.ProcessorCount可能更好