我在我的Windows窗體C#應用這些代碼:並行功能,在C#中返回不同的結果
private void button7_Click(object sender, EventArgs e)
{
ThreadStart starter = delegate { thread_func(2, 1000000); };
thread1_thread = new Thread(starter);
starter = delegate { thread_func(1000000, 2000000); };
thread2_thread = new Thread(starter);
starter = delegate { thread_func(2000000, 3000000); };
thread3_thread = new Thread(starter);
starter = delegate { thread_func(3000000, 4000000); };
thread4_thread = new Thread(starter);
thread1_thread.Start();
thread2_thread.Start();
thread3_thread.Start();
thread4_thread.Start();
}
void thread_func(decimal input1,decimal input2)
{
for (; input1 < input2; input1++)
{
threadNumbers_list.Add(input1);
if (input1 % 2 != 0)
{
if (isPrime_func(input1))
{
PrimeNumbers_decimal_list.Add(input1);
}
}
}
}
public static Boolean isPrime_func(decimal number)
{
decimal boundary = (decimal)Math.Floor(Math.Sqrt((double)number));
if (number == 1) return false;
if (number == 2) return true;
for (decimal i = 2; i <= boundary; ++i)
{
if (number % i == 0) return false;
}
return true;
}
我每次運行單擊該按鈕,我得到不同的結果。我嘗試了很多東西,但無法弄清楚爲什麼會發生這種情況。即使是在較低的範圍內發生。例如,在100個數字的範圍內,它總是給出相同的結果。 有些時候,我的清單計數達到283138,有時候是283131和其他接近的數字。
另一個奇怪的是,當我評論檢查偶數時,操作比此模式花費的時間更短。怎麼了?
'threadNumbers_list'和'PrimeNumbers_decimal_list'可能不是線程安全的。 –
我創建該列表只是爲了檢查是否所有迭代都發生! – ACE
'PrimeNumbers_decimal_list'呢?另外,你如何等待線程完成?你使用'Thread.Join'嗎? –