簡體   English   中英

使用不帶列表的 Parallel.ForEach

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM