當我開發Windows服務時,我遇到了一個奇怪的情況。For循環原因IndexOutOfBoundException
我有一個MonitorOutputFile,其中我實現了方法MonitorOutputFile中的FileSystemWatcher。
當我寫的代碼如下
foreach (string filePath in filePathValue)
{new Thread(() => monitorController.MonitorOutputFile(filePath, pollRetryInterval, fileWaitTime)).Start();}
- >它運作良好的的OnStart();
然而,當我使用
for(int i=0;i<filePathValue.Length;i++)
{
new Thread(() => monitorController.MonitorOutputFile(filePathValue[i], pollRetryInterval, fileWaitTime)).Start();
}
- >這擲IndexOutOfBoundException在的OnStart()方法。
我地合計這是我的問題,所以我做了輸出
for(int i=0;i<filePathValue.Length;i++)
{
EventLog.WriteEntry(SourceName, filePathValue[i], EventLogEntryType.Information, 58987);
}
- >此能夠輸出filePathValue [I]的正確的輸出。
不像Thread causing IndexOutOfBoundException 這是期待一個返回值,我的Windows服務不會等待任何返回值。這兩個有相似之處嗎?
有人可以告訴我爲什麼會發生這種情況?希望有人能夠與我分享這個奇怪的案例。
我希望標記所有答案,這有助於我更多地瞭解lambda。謝謝大家:)星期五歡呼。 –