【问题标题】:Use Parallel.ForEach without lists使用没有列表的 Parallel.ForEach
【发布时间】:2018-08-14 21:48:43
【问题描述】:

我想使用Parallel.ForEach 作为多线程方法,无需列表或文件读取即可执行代码。

我想这样做:

Parallel.ForEach
{
      Console.WriteLine("test");
}

所以它会不停地写test。我将使用IF 语句来检查它是否应该停止。

可以这样使用Parallel.ForEach吗?

任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • 为什么要使用 foreach 循环而不需要任何迭代?这里的主要目标是什么? ForEach 似乎无关紧要。
  • @SelmanGenç - 我希望它执行未在列表上迭代的普通代码。
  • 为什么要使用构造来遍历您没有的列表?请解释你将如何使用普通的foreach
  • @NirmalSubedi - 我希望它是多线程的。
  • 而不是检查 if 语句中的某些条件(正如您在问题中提到的那样),您可以将其用作循环的条件:while (someCondition == true) { Console.WriteLine("Test"); }

标签: c# multithreading parallel.foreach


【解决方案1】:

多线程这不会实现任何目标,但如果你坚持:

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");
}

【讨论】:

  • 此外,我强烈建议您更新到旧线程的任务 API。
【解决方案2】:

你想要的不是很清楚,但你可以试试这个方法:

        var parallelDrege = Environment.ProcessorCount;
        while (true)
        {
            Parallel.For(0, parallelDrege, t =>
            {
                Console.WriteLine("test");
            });
        }

将parallelDegre 设置为所需的值,并注意每个批次都将并行处理,但从批次到批次是一个连续的过程。

希望对您有所帮助!

【讨论】:

  • 我如何终止这个?
  • 随 CPU 数量而变化
  • Environment.ProcessorCount
  • 或者这个因素:2*Environment.ProcessorCount 可能更好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多