我想要什麼來實現的:Paralle.For最大線程數和當前線程C#
使用的Parallel.For(別的,將不勝感激,卻發現了這是一個最簡單的),我想增加一個名爲變量最大,使其得到100000000,使用線程,但計劃應在同一時間只能使用線程的X個。
一小段代碼片段:
using System;
using System.Threading;
using System.Linq;
using System.Threading.Tasks;
using System.Diagnostics;
namespace pool_threading
{
class MainClass
{
static int max=0;
static int current_max_thread=0;
public static void Main (string[] args)
{
Parallel.For(0, 100000000, new ParallelOptions { MaxDegreeOfParallelism = 50 },
i =>
{
max++;
if(Thread.CurrentThread.ManagedThreadId>current_max_thread)
current_max_thread=Thread.CurrentThread.ManagedThreadId;
});
Console.WriteLine ("I got to this number {0} using most {1} threads",max,current_max_tread);
}
public static void GetPage(int i)
{
}
}
}
結果:
我使用最多11個線程
現在這個數字38786886 ......我不知道爲什麼我得到小於38786886的數字38786886,但我想這是因爲多個線程試圖在同一個ti處增加它我,所以如果10個人在同一時間嘗試,只有第一個人會有機會。如果我錯了,請糾正我。
最大的「問題」是,我得到11個線程的時候,即使是最大設定到50(滾動碼看最大),如果將它設置爲最高1線,我總是得到4(也許4是這種情況下的最小值,但它仍然不能解釋爲什麼我同時只能得到11個最大值)。
爲什麼你需要完全'X'的線程數? – jamesthollowell