【问题标题】:Issue when using MultiThreading in C#在 C# 中使用多线程时出现问题
【发布时间】:2022-11-21 05:09:42
【问题描述】:

我有一个包含 125 行的文件:

blue
black
yellow
...
purple

我想创建 5 个线程,这 5 个线程将占用文件中的 25 行不同的行并将它们打印到控制台窗口,只要它们打印每一行,它们是否不按升序打印并不重要。

我试过的代码如下所示:

        string[] colors = File.ReadAllLines("colors.txt");
        Thread[] threads = new Thread[5];
        Console.WriteLine(threads.Length); // 5

        for (int i = 0; i < threads.Length; i++)
        {
            int indexStart = (colors.Length) * i / threads.Length;
            int indexStop = (colors.Length) * (i + 1) / threads.Length;
            new Thread(() =>
            {
                for (int j = indexStart; j < indexStop; j++)
                {
                    Console.WriteLine(colors[j]);
                }
            }).Start();
        }

        Console.ReadLine();

看起来运行程序时它和单线程程序一样快,我做错了什么?

【问题讨论】:

  • 这将由序列化的 Console.WriteLine 调用主导。

标签: c# multithreading


【解决方案1】:

我猜这是因为只有一个线程可以访问控制台以写出结果。当然,控制台是线程安全的,它们不会相互干扰,但您不可能同时从 2 个或更多线程写入。一般来说,输入/输出操作是序列化的,这也适用于控制台输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多