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

本文关键字:返回值 问题 多线程 | 更新日期: 2023-09-27 18:20:11

我觉得我做错了什么,但我不知道是什么。当我运行此代码时,两个线程(thread1和thread2)立即不活动,但val1和val2中的值没有正确设置。

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

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

您创建了线程,但没有启动它们。创建后调用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();