我想用多线程来读/写文本文件来加速我的工具这是我如何开始的 - 我想我需要 7 个线程
for (int i = 0; i < 7; i++)
{
Thread thread = new Thread(() => process(files[i], i));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
而我的函数
void process(string file,int threadnumber)
{
// display thread number
// filter text
// read - write
}
但是当我开始的时候:
Thread: 3 start
Thread: 3 start
Thread: 3 start
Thread: 4 start
Thread: 5 start
Thread: 6 start
Thread: 7 start
为什么我的工具不启动线程 1 2 3 4 5 6 7.. 很少有线程重复 - 这意味着读取和写入相同的文件和错误。
请给我建议。
根据循环迭代的速度和线程启动的速度,当线程实际启动时,i
变量可能已经更改。
您必须为每个线程声明一个未更改的新变量:
for (int i = 0; i < 7; i++)
{
int j = i; //New variable set to the current 'i'.
Thread thread = new Thread(() => process(files[j], j));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
在上面,j
变量将获得与当前i
相同的值,并且即使循环继续迭代也不会改变。