代码之家  ›  专栏  ›  技术社区  ›  Mario

使用parallel.foreach而不使用列表

  •  -3
  • Mario  · 技术社区  · 8 年前

    我想用 Parallel.ForEach 作为一种多线程方法,执行一个没有列表或文件读取的代码。

    我想这样做:

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

    所以它会写 test 没有停止。我会用一个 IF 检查是否应该停止的语句。

    可以用吗 并行循环 像那样?

    任何帮助都将不胜感激。

    谢谢!

    2 回复  |  直到 8 年前
        1
  •  0
  •   Miguel    8 年前

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

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

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

    希望能帮上忙!

        2
  •  1
  •   Daniel Loudon    8 年前

    多线程这不会取得任何效果,但如果您坚持:

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