【发布时间】: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