Quando si avviano più thread, il parametro id
viene analizzato a volte errato. Qui è la mia startup:Parametri della filettatura modificati
for (int i = 0; i < _threadCount; i++)
{
Thread thread = new Thread(() => WorkerThread(i));
thread.Start();
_threads.Add(thread);
}
E la mia funzione di discussione:
private void WorkerThread(int id)
{
Console.WriteLine("[{0}] Thread started {1}", DateTime.Now.ToLongTimeString(), id);
}
L'uscita di questo codice è:
[19:10:54] Thread start 3
[19:10:54] Thread start 9
[19:10:54] Thread start 4
[19:10:54] Thread start 12
[19:10:54] Thread start 11
[19:10:54] Thread start 3
[19:10:54] Thread start 12
[19:10:54] Thread start 6
[19:10:54] Thread start 9
[19:10:54] Thread start 6
[19:10:54] Thread start 13
[19:10:54] Thread start 2
[19:10:54] Thread start 15
[19:10:54] Thread start 9
[19:10:54] Thread start 15
Dove nella mia mente, questo codice dovrebbe creare ogni thread con un unico id
invece di duplicati come visto sopra.
Compiler informazioni: obiettivo
Piattaforma: x64
target Framework: .NET Framework 4.5
Tutti i thread condividono la stessa variabile. – SLaks
Qualcuno in realtà ha appena postato una domanda simile, ecco un articolo collegato di Eric Lippert sull'argomento. http://ericlippert.com/2009/11/12/close-over-the-loop-variable-considered-harmful-part-one/ – KDecker