當我運行下面的代碼片段時,拋出了IndexOutOfRangeException。看起來,當拋出異常時,我是2。我的理解是,新的線程在i的值被改變後開始。有沒有辦法讓這個代碼安全的這種問題?啓動新線程時拋出IndexOutOfRangeException
int x[2] = {1, 3};
int numberOfThreads = 2;
for (int i = 0; i < numberOfThreads; i++)
{
new Thread(() =>
{
DoWork(x[i]);
}).Start();
}
可能重複: //stackoverflow.com/questions/2741870/for-loop-index-out-of-range-argumentoutofrangeexception-when-multithreading) –