0
我想我正在做一些令人難以置信的錯誤,但我不知道是什麼。當我運行這段代碼時,兩個線程(thread1和thread2)立即無法生效,但val1和val2中的值沒有正確設置。c#中返回值的多線程問題
不在線程中的代碼部分工作,如果我調用級別= 0的進程,我會在val1和val2中得到兩個正確的結果。
public int Process(int left, int right, List<int> array, int level)
{
int val1, val2;
val1 = 0;
val2 = 0;
int val = array[left] + array[right] + (right - left);
if (level > 0)
{
if ((right - left) > 1)
{
var thread1 = new Thread(() => { val1 = Process(left, right - 1, array, level - 1); });
var thread2 = new Thread(() => { val2 = Process(left - 1, right, array, level - 1); });
while (thread1.IsAlive)
{
System.Threading.Thread.Sleep(100);
}
while (thread2.IsAlive)
{
System.Threading.Thread.Sleep(100);
}
val = Math.Max(Math.Max(val1, val2), val);
}
}
else
{
if ((right - left) > 1)
{
val1 = Process(left, right - 1, array, level);
val2 = Process(left + 1, right, array, level);
val = Math.Max(Math.Max(val1, val2), val);
}
}
return val;
}
就是這樣!我知道這是愚蠢的! – SeraphimFoA 2014-09-01 16:42:00