带有返回值的c#问题中的多线程

时间:2014-09-01 16:30:58

标签: c# multithreading

我认为我做了一件令人难以置信的错事,但我不知道是什么。当我运行此代码时,两个线程(thread1和thread2)立即生效,但val1和val2中的值未正确设置。

不在线程中的代码部分工作,如果我调用Process为level = 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;
    }

1 个答案:

答案 0 :(得分:2)

您创建了线程,但没有启动它们。创建后调用Thread.Start()。

var thread1 = new Thread(() => { val1 = Process(left, right - 1, array, level - 1); });
var thread2 = new Thread(() => { val2 = Process(left - 1, right, array, level - 1); });
thread1.Start();
thread2.Start();