0
餘萬,以加快我的多線程工具來讀/寫文本文件 在這裏,我怎麼開始 - 我想我需要7線程C#多線程和讀/寫大的文本文件
for (int i = 0; i < 7; i++)
{
Thread thread = new Thread(() => process(files[i], i));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
和我FUNC
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 ..幾線程重複 - 意味着讀取和寫入相同的文件和錯誤。
請給我建議。
哪個C#版本? –
你只有1個「我」。在時間i = 3時,啓動線程0,1和2。所以,當時我是3.在多線程中總是同步的,例如:files [i]和i。如果你運行這個內部線程:「Console.WriteLine(Thread.CurrentThread.ManagedThreadId);」那麼你可以看到,每個線程都有不同的id。 –
捕獲for循環變量是[標準C#bug](https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/) 。 –