C# 如何在两个基本线程中显示随机结果

C# 如何在两个基本线程中显示随机结果,c#,multithreading,C#,Multithreading,我有一个列表测试,为了进行测试,我需要制作基本线程,一个用于填充,另一个用于随机显示来自同一个线程的项目。所以,任务是在控制台中随机填充和显示结果。当然,问题是我的显示方法将该列表作为参数,因此可能需要解决相同的实例。这是我的代码,它只是填充,然后显示项目: static void Main(string[] args) { List<int> testList = new List<int>();

我有一个列表测试,为了进行测试,我需要制作基本线程,一个用于填充,另一个用于随机显示来自同一个线程的项目。所以,任务是在控制台中随机填充和显示结果。当然,问题是我的显示方法将该列表作为参数,因此可能需要解决相同的实例。这是我的代码,它只是填充,然后显示项目:

        static void Main(string[] args)
        {
            List<int> testList = new List<int>();
            System.Threading.Thread.Sleep(300);
            for (int y = 0; y < 50; y++)
            {
                testList.Add(y);
                Console.WriteLine(string.Format("Added item {0}!", y));
            };

            Thread testThread1 = new Thread(() => FillList(testList));
            testThread1.Start();
            Console.ReadKey();
        }

        public static void FillList(List<int> pTestList)
        {
            foreach(int x in pTestList)
            {
                System.Threading.Thread.Sleep(1000);
                Console.WriteLine(x.ToString());
            }
        }
更新:

我想在我的控制台中显示几个添加的项和项。所以要混合图像中的第一部分和第二部分

我将使用具有可变位置的Struct或object。 然后代码可能看起来像:

        static void Main(string[] args)
        {
            List<int> testList = new List<int>();
            System.Threading.Thread.Sleep(300);
            Random rng = new Random(123);
            for (int y = 0; y < 50; y++)
            {
                testList.Add(y);
                Console.WriteLine(string.Format("Added item {0}!", y));
            };

            Thread testThread1 = new Thread(() => FillList(testList));
            testThread1.Start();
            Console.ReadKey();
        }

        public static void FillList(List<int> pTestList)
        {
            List<Number> testList = new List<Number>();
            Random rng = new Random(123);
            foreach (var item in pTestList)
            {
                testList.Add(new Number() { IntNumber = item, Position = rng.Next() });
            }

            foreach (Number x in testList.OrderBy(x => x.Position))
            {
                System.Threading.Thread.Sleep(1000);
                Console.WriteLine(x.IntNumber);
            }
        }

        public struct Number
        {
            public int Position { get; set; }
            public int IntNumber { get; set; }
        }

当您传递或使用列表时,您可以随机对列表排序/洗牌,无论您喜欢哪个:我需要使用线程。这就是重点@对不起,这个问题有点不清楚你在哪一方面遇到了麻烦。你的意思是:你想在一个单独的线程中填充列表,并且需要确保在开始随机显示项目的线程之前完成了该操作?我认为,因为你没有随机显示任何内容,所以这个问题是关于随机部分的。@DavidPine这样的声明真的需要引用……亲爱的,你能修正你的投票吗,因为我的帐户被禁止了。多谢各位@Austinsalonen您的代码工作得很好,但这不是我想要实现的。我想展示一下第一个线程和第二个线程之间的相互交织。当然,如果可能的话。“随机”一词与此有关@你的意思是像拆分数字列表并将其写入更多线程?像拆分第一个线程和第二个线程的结果。我不确定是否有人理解我想问的问题@斯拉斯科