2016-07-09 22 views
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 ..幾線程重複 - 意味着讀取和寫入相同的文件和錯誤。

請給我建議。

+2

哪個C#版本? –

+0

你只有1個「我」。在時間i = 3時,啓動線程0,1和2。所以,當時我是3.在多線程中總是同步的,例如:files [i]和i。如果你運行這個內部線程:「Console.WriteLine(Thread.CurrentThread.ManagedThreadId);」那麼你可以看到,每個線程都有不同的id。 –

+3

捕獲for循環變量是[標準C#bug](https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/) 。 –

回答

0

根據循環迭代的速度和線程啓動速度有多快,線程實際啓動時可能會發生變化。

您必須聲明一個新的變量,每個線程,也就是沒有改變:

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 -variable將獲得相同的值作爲當前i,甚至不會改變如果循環繼續迭代。